1

I'd like to create a shortcode that would display the post count for a specific category within a custom post type. I've been trying to alter the code below but need some help. Could anyone let me know how to tweak so that the shortcode is for a specific custom post type.

// Add Shortcode to show posts count inside a category
function category_post_count( $atts ) {

    $atts = shortcode_atts( array(
        'category' => null
    ), $atts );

    // get the category by slug.
    $term = get_term_by( 'slug', $atts['category'], 'category');

    return ( isset( $term->count ) ) ? $term->count : 0;
}
add_shortcode( 'category_post_count', 'category_post_count' );

Thanks in advance!

2 Answers 2

0

I think you would be better off using get_posts or a new WP_Query instead of get_term_by. That would allow you to get posts for your custom post type, and then filter by taxonomy/term name.

If you're comfortable enough with WP Query you could try something like this: Query posts by taxonomy term name

0

If for some reason you're using the shortcode inside the loop, you could try the code below. Failing that, your best bet is to get to grips with WP_Query as suggested in another answer.

Add to functions.php

function category_post_count( $atts ) {

    $atts = shortcode_atts( array(
        'category' => null,
        'type' => null
    ), $atts );

    $term = get_term_by( 'slug', $atts['category'], 'category');
    $tpt = $atts['type'];

    if( get_post_type() == $tpt ) {
        return $term->count;
    }

}
add_shortcode( 'category_post_count', 'category_post_count' );

Typical usage

[category_post_count category="category_slug" type="post_type"]
3
  • Thanks for providing the above code. It is within the loop but for some reason the above did not work? I have a custom post type, and have a handful of categories for the custom post type. Wanted to display the category count number on the page with a shortcode. But for some reason it's not pulling anything.
    – Northtime
    Nov 16, 2017 at 3:28
  • If it didn't display anything, make sure you've replaced post_type with the correct post_type - if both the category_slug and post_type are entered correctly, there's no reason why it wouldn't work. Can you double check? Correct usage should look like [category_post_count category="genre" type="movies"] where genre would be the slug of a category and movies is the name of your custom post type. Nov 16, 2017 at 9:02
  • Yes unfortunately the slug and post type are all correct in my shortcode. Not sure what's going on? Been searching for different solution today.
    – Northtime
    Nov 16, 2017 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.