I have this WP Query running for each row in my admin screen for a certain post type:
$entry_args = array(
'meta_key' => 'wp_comp_entry_competition-id',
'meta_value' => $post_ID,
'post_type' => 'wp_comp_entries'
);
$entry_query = new WP_Query( $entry_args );
This WP Query fetches all entries for a competition identified by the $post_ID
. There is a lot of data since a single competition will have thousands entries.
In consequence, this query repeated multiple times (for each row in an admin screen) is rather slow. Moreover, I do not need all this data. I only want to know the number of entries for each competition identified by $post_ID
.
I assume that the way to fetch only the COUNT
of entries would be changing this WP Query into a simpler, direct SQL query on WordPress database.
How can I fetch only the number of entries for each competition and not all post data associated with each entry?
Further explanation:
I've now tried fetching only the count of posts with these two approaches:
1) Passing 'fields' => 'ids'
to query arguments
$entry_args = array(
'meta_key' => 'wp_comp_entry_competition-id',
'meta_value' => $post_ID,
'post_type' => 'wp_comp_entries',
'fields' => 'ids'
);
$entry_query = new WP_Query( $entry_args );
and then using $entry_qyery->found->posts
to get the number, and
2) Using query_posts
like this:
$entry_args = array(
'meta_key' => 'wp_comp_entry_competition-id',
'meta_value' => $post_ID,
'post_type' => 'wp_comp_entries',
'fields' => 'ids',
'posts_per_page' => -1
);
$entry_query = query_posts( $entry_args );
and then using count($entry_query)
to count all fetched ids (as query_posts
returned an array).
My first experience is that query_posts
was much slower than WP Query
in this case.
'fields' => 'ids'
to return only the post IDs ? Here's another way, "changing this WP Query into a simpler, direct SQL query"WP_Query
will still try to find all matching posts according to query in order to count them for pagination purposes. We can then still use$entry_query->found_posts
to get the correct post count for the specific query ;-)'fields' => 'ids',
to my WP Query argumets array. I'm still using$entry_query->found_posts
to display the count of posts. I think that this should improve performance as onlyids
are fetched.ids
of selected posts with'fields' => 'ids'
will not bring a performance improvement?posts_per_page
parameter to just1
andfields
toids
. This will return 1 post ID, but$found_posts
should still return a post count of all matching posts. This is how pagination is calculated. It does not matter how many posts you query,WP_Query
still goes through the complete db counting all matching posts and stores the post count as$found_posts
. This is used to calculate pagination.