custom post type category count shortcode

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!

Topic shortcode count posts custom-post-types Wordpress

Category Web


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"]

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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.