0
votes

I am trying to make a WordPress shortcode that should show a text containing the number of posts in a specific category and if the category is empty it should return a text saying that the category is empty.

The shortcode I have made so far kinda works. The only problem is that it keeps returning 0 posts even though there are numerous posts in that specific category.

I have tried different functions such as is_category() and get_category() but neither works. Does it make any difference that the category is related to a custom post type? The post type slug is 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' );
2
Although not intuitive, you should be using the get_terms function to get a category by name. See @TheDeadMedic's answer hereJamie_D
something like this? get_terms( 'category', array( 'search' => 'aaben-projekt' ) ); - It doesn't seem to do any difference.TurboTobias

2 Answers

0
votes

Another way to achieve the required result would be to use the WP_QUERY as below.

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

I manged to find a solution to my own question by using WP_QUERY instead of get_category() and post_count instead of just 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' );