Created
September 28, 2020 19:48
-
-
Save petenelson/a418436ede95cd2f04ad00e9ee0e22ce to your computer and use it in GitHub Desktop.
WordPress: Get paginated query results.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Runs WP_Query and gets all results using pagination. | |
* | |
* @param array $query_args List of WP_Query args. | |
* @return array | |
*/ | |
function get_paginated_query_results( $query_args ) { | |
$results = []; | |
if ( ! isset( $query_args['posts_per_page'] ) ) { | |
$query_args['posts_per_page'] = 50; | |
} | |
if ( ! isset( $query_args['paged'] ) ) { | |
$query_args['paged'] = 1; | |
} | |
if ( ! isset( $query_args['update_post_meta_cache'] ) ) { | |
$query_args['update_post_meta_cache'] = false; | |
} | |
if ( ! isset( $query_args['update_term_meta_cache'] ) ) { | |
$query_args['update_term_meta_cache'] = false; | |
} | |
$query = new \WP_Query( $query_args ); | |
while ( $query->have_posts() ) { | |
$results = array_merge( $results, $query->posts ); | |
if ( $query->max_num_pages > 1 ) { | |
$query_args['paged']++; | |
$query = new \WP_Query( $query_args ); | |
} else { | |
break; | |
} | |
} | |
return $results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment