获取自定义帖子类型计数的查询对象

时间:2019-07-26 作者:Gidromasservis QSC

$posts = get_queried_object();
echo $posts->count;
我可以在分类法归档页面中使用此代码获取帖子计数。问题是我不能指定post类型。我只想数一个自定义的帖子类型。

我试着这样做:

$posts = get_queried_object(
$args = array(
  \'post_type\' => \'custom-post\'
));
$the_query = new WP_Query( $args );
echo $the_query->found_posts;
但此代码显示总自定义帖子类型计数

1 个回复
最合适的回答,由SO网友:Gidromasservis QSC 整理而成
    function wpse340250_term_count( WP_Term $term, $post_type) {
    $q_args = [
        \'post_type\' => $post_type,
        \'nopaging\' => true, // no limit, pagination
        \'fields\' => \'ids\', // only return post id\'s instead of full WP_Post objects will speed up
        \'tax_query\' => array(
            array(
                \'taxonomy\' => $term->taxonomy,
                \'field\'    => \'term_id\',
                \'terms\'    => $term->term_id,
            ),
        ),
    ];
    $term_count = get_posts($q_args);

    return count($term_count);
}
<?php

// get the terms you need
$terms = get_terms( $posts = get_queried_object());
$sorted_terms = [];
if ( $terms ) {
    foreach ( $terms as $term ) {
        $sorted_term = [

            \'count\'              => (int) wpse340250_term_count( $term, \'Custom-post\' ),
            // everything you will need later here
        ];

        // here handle all dynamic checks add them to $sorted_term
        if ( $term->taxonomy == \'category\' && is_category() ) {
            $thisCat = get_category( get_query_var( \'cat\' ), false );
            if ( $thisCat->term_id == $term->term_id ) {
                $sorted_term[\'carrentActiveClass\'] = \'class="active-cat"\';
            }
        }

        // for the sake of getting to the core of the answer I left stuff out.


        // add the complete sorted_term to the collection
        $sorted_terms[] = $sorted_term;
    }


}
// all done gathering data now we handle html output
?>
                       <?php echo $sorted_term[\'count\'] ?>