I'm wondering how I can request the amount of posts by passing certain arguments (you could see this as part of a "query"). See the example below.
$args = [
"numberposts" => -1,
"post_type" => "jobs",
"s" => "developer",
"tax_query" => ["taxonomy" => "IT", "field" => "slug"]
];
$posts = get_posts($args);
$count = count($posts);
I'm aware of the fact that the following function works perfectly for my case. However, it's extremely exhausting to execute. Instead of actually getting all posts within a query, I'm just looking for a function that just counts the posts with certain arguments.
Please bare in mind that I'm passing on certain meta_queries and tax_queries which will make some queries to the database fairly hard on itself already.
Hope someone can help.
I'm wondering how I can request the amount of posts by passing certain arguments (you could see this as part of a "query"). See the example below.
$args = [
"numberposts" => -1,
"post_type" => "jobs",
"s" => "developer",
"tax_query" => ["taxonomy" => "IT", "field" => "slug"]
];
$posts = get_posts($args);
$count = count($posts);
I'm aware of the fact that the following function works perfectly for my case. However, it's extremely exhausting to execute. Instead of actually getting all posts within a query, I'm just looking for a function that just counts the posts with certain arguments.
Please bare in mind that I'm passing on certain meta_queries and tax_queries which will make some queries to the database fairly hard on itself already.
Hope someone can help.
The easiest way to optimize this query would be to add 'fields' => 'ids'
to the arguments. This way only ids of posts will be retrieved from DB (and usually that’s a big change).
$args = [
'numberposts' => -1,
'post_type' => 'jobs',
's' => 'developer',
'tax_query' => ['taxonomy' => 'IT', 'field' => 'slug'],
'fields' => 'ids'
];
$posts = get_posts($args);
$count = count($posts);
On the other hand you can use WP_Query
instead of get_posts
. This way you can set posts_per_page
to 1, so only one ID will be retrieved and use found_posts
field of WP_Query to get the total number of posts matching your criteria.
$args = [
'posts_per_page' => 1,
'post_type' => 'jobs',
's' => 'developer',
'tax_query' => ['taxonomy' => 'IT', 'field' => 'slug'],
'fields' => 'ids'
];
$query = new WP_Query($args);
$count = $query->found_posts;