PHP 基于类别中帖子数量的文本

PHP text based on number of posts in category

我正在尝试制作一个 WordPress 简码,它应该显示包含特定类别中 post 数量的文本,如果该类别为空,它应该 return 一个文本说明类别为空。

到目前为止我制作的简码还算管用。唯一的问题是它保持 returning 0 post,即使在该特定类别中有许多 post。

我尝试了不同的函数,例如 is_category() 和 get_category(),但都不起作用。该类别与自定义 post 类型相关是否有任何区别? post 类型 slug 是 projekt btw.

function imbro_aaben_projekt_shortcode() {
    $category = get_category('aaben-projekt');
    $theCount = $category->count;

    if ( $theCount > 0 ){

        return 'Total: ' . $theCount . ' posts in this category';

    } else {

        return 'There are no posts in this category';

    }
}

add_shortcode( 'imbro_empty', 'imbro_aaben_projekt_shortcode' );

另一种实现所需结果的方法是使用如下 WP_QUERY

   $args = array(
       'cat' => 4, // category id
       'post_type' => 'post'
    );
    $the_query = new WP_Query( $args );
    echo $the_query->found_posts;

我设法通过使用 WP_QUERY 而不是 get_category() 和 post_count 而不是仅仅计数来找到解决我自己问题的方法:

function imbro_aaben_projekt_shortcode() {
       $args = array(
       'cat' => 1, // category id
       'post_type' => 'projekt'
    );
    $the_query = new WP_Query( $args );
    $theCount = $the_query->post_count;

    if ( $theCount > 0 ){

        return 'Total: ' . $theCount . ' posts in this category';

    } else {

        return 'There are no posts in this category';

    }
}

add_shortcode( 'imbro_empty', 'imbro_aaben_projekt_shortcode' );