WP查询帖子计数始终为0

时间:2019-05-16 08:40:09

标签: wordpress api

我的数据库中有很多计划的帖子(位置),并且我只想显示已发布帖子的分类法(位置类型)。

因此,我创建了一个check_term_posts($ term_id)函数

但它总是返回0。

WP查询似乎是完成此任务的唯一方法,因为$ term-> count似乎可以提供所有内容。

    protected function check_term_posts($term_id) {
            $args = [
                'posts_per_page' => -1,
                'post_type' => 'location',
                'post_status' => 'publish',
                'tax_query' => [[
                    'taxonomy' => 'locationtype',
                    'field' => 'term_id',
                    'terms' => $term_id
                ]]
            ];

            $q = new \WP_Query($args);
            return $q->post_count;
    }

$ q-> post_count始终为零

1 个答案:

答案 0 :(得分:1)

您必须替换

'field' => 'term_id', to 'field' => 'id',

您的代码变成这样

$args = [
                'posts_per_page' => -1,
                'post_type' => 'location',
                'post_status' => 'publish',
                'tax_query' => [[
                    'taxonomy' => 'locationtype',
                    'field' => 'id',
                    'terms' => $term_id
                ]]
            ];