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:
- Get the next page url
- Parse it to get query parameters of next page
- 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:
Category: WordPress