I want to get all post IDs from the current query. I know how to get all IDs of the current page using the following:
global $wp_query;
$post_ids = wp_list_pluck( $wp_query->posts, "ID" );
This will give me an array of all post IDs, but limited to the current page.
How can I get all IDs but not limited by 'posts_per_page'
. (I don’t want to modify the query by changing ‘posts_per_page’.)
I know that there is already information available from the global $wp_query
such as:
We will be displaying ” . $wp_query->query_vars['posts_per_page'] .
” posts per page if possible.
We need a total of ” . $wp_query->max_num_pages .
” pages to display the results.
Additional Details:
I am trying to get WooCommerce product IDs and hooking into the woocommerce_archive_description
action to do this.
2 Answers
Slightly old post I know but I just hit this exact issue myself.
Given a main_query find all the post IDs for it not limited by pagination.
I have made this function to return all terms for the main wp_query.
/*
* Get terms for a given wp_query no paging
* */
function get_terms_for_current_posts($tax='post_tag',$the_wp_query=false){
global $wp_query;
// Use global WP_Query but option to override
$q = $wp_query;
if($the_wp_query){
$q = $the_wp_query;
}
$q->query_vars['posts_per_page'] = 200;// setting -1 does not seem to work here?
$q->query_vars['fields'] = 'ids';// I only want the post IDs
$the_query = new WP_Query($q->query_vars);// get the posts
// $the_query->posts is an array of all found post IDs
// get all terms for the given array of post IDs
$y = wp_get_object_terms( $the_query->posts, $tax );
return $y;// array of term objects
}
Hope this helps you or someone else stumbling across this.