Abhineet.in

unlearning the learnt

Menu
  • Home
  • About
  • CAT Preparation
Menu

WP_Query by URL for Infinite Scroll in WordPress

Posted on June 15, 2022April 5, 2023 by Abhineet Mittal

I was trying to create an infinite scroll in WordPress. All I wanted was to parse the next page url without making any changes to the code so that the code becomes interoperable with the pagination templates.

To achieve that, instead of passing custom query parameters to the API, I decided to parse the next page url to run WP_Query without mentioning any additional parameters.

Steps were:

  1. Get the next page url
  2. Parse it to get query parameters of next page
  3. Run WP_Query on that and get the posts of next page

Though I spent hours on this, it turned out to be rather simple.

// Get the url of the next page
$next_page_url = $args[ 'next_page_url' ] ?? $_SERVER['REQUEST_URI'];

// Save the next page url in the current global server variable array $_SERVER['REQUEST_URI'] = $current_page_url;

// Rebuild the global $_GET variable to include the new query string parameters parse_str( parse_url( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ?? '', PHP_URL_QUERY ), $_GET );

// Run the wp_query to get the posts of next page $wp->parse_request(); $wp->query_posts(); $all_posts = $wp_query->posts;

Just replace your pagination links with an element which passes the next page url to the API when it becomes visible. And you can get the posts HTML from the API.

And that’s it. Your infinite scroll is ready.

References:

  1. https://medium.com/@harryhorton/query-wp-rest-api-using-any-permalink-url-f5e4e4dd36b7
Category: WordPress

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Business
  • CAT Preparation
  • Coding
  • Fiction
  • Finance
  • How-To-Life
  • Javascript
  • Life
  • Life at Infosys
  • Photoshop
  • Productivity
  • Publishing
  • Reading
  • Social Awareness
  • Startup
  • Technology
  • Uncategorized
  • Utilities
  • Visual Studio Code
  • Web Development
  • WordPress
  • Work Culture

Recent Posts

  • Book Review: The Great Gatsby
  • The Ultimate Guide to CAT Preparation: Tips and Tricks
  • Self-Publishing vs. Traditional Publishing: Which Is Right for You?
  • 7 Effective Strategies to Overcome Procrastination and Achieve Your Goals
  • How to detect English/ASCII string in PHP

Recent Comments

  • Rohan George on Intermediate, Stream & Location: Luck by Chance
  • Ashika on Intermediate, Stream & Location: Luck by Chance
  • Steve on My first job, Infosys
  • SAKTHI on Finally, its Mysore…
  • Akash dhyani Akash on Training Begins…
© 2023 Abhineet.in | Powered by Minimalist Blog WordPress Theme