优化此查询的最简单方法是添加\'fields\' => \'ids\'
到参数。这样,只会从DB中检索帖子的ID(通常这是一个很大的变化)。
$args = [
\'numberposts\' => -1,
\'post_type\' => \'jobs\',
\'s\' => \'developer\',
\'tax_query\' => [\'taxonomy\' => \'IT\', \'field\' => \'slug\'],
\'fields\' => \'ids\'
];
$posts = get_posts($args);
$count = count($posts);
另一方面,您可以使用
WP_Query
而不是
get_posts
. 这样可以设置
posts_per_page
设置为1,因此仅检索和使用一个ID
found_posts
WP\\u查询字段,以获取与您的条件匹配的帖子总数。
$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;