Site logo

[Resolved] Show post counts with category name

Home Forums Support [Resolved] Show post counts with category name

Home Forums Support Show post counts with category name

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #2495936
    Pankaj

    Hello,

    I want to show the number of posts in a category.

    I have shared the website link and screenshot for the reference.

    Any support person can please help me with this?

    Regards

    #2496100
    David
    Staff
    Customer Support

    Hi there,

    if you want to add that kind of data to your design, you will need to create a shortcode that you can add to your site.

    1. Add this PHP Snippet to your site:

    // 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' );

    2. In a GB Headline block add the shortcode ie. [category_post_count category="category_slug_or_name"]
    Where it says the category_slug_or_name change that to the term slug that you want to display the count for.

    For reference and kudos, this is where that code came from:

    https://wordpress.stackexchange.com/a/240763

    #2496852
    Pankaj

    Hello,

    This fixed what I was looking.

    Regards

    #2497246
    David
    Staff
    Customer Support

    Glad to hear that!

    #2498048
    Andreas

    Hello, it works with categorys perfect – what have i to change, that it also works with tags? So that i see the number of posts with a tag. When i replace ‘category’ with ‘tag’ or ‘post_tag’ in this code, it doesn’t work. Can you give a hint please? Thank you.

    #2498059
    Andreas

    After try and error – i think, this is the solution:

    function tag_post_count( $atts ) {
        $atts = shortcode_atts( array(
            'tag' => null
        ), $atts );
        // get the tag by slug.
        $term = get_term_by( 'slug', $atts['tag'], 'post_tag');
        return ( isset( $term->count ) ) ? $term->count : 0;
    }
    add_shortcode( 'tag_post_count', 'tag_post_count' );
    #2498077
    Leo
    Staff
    Customer Support

    Thanks for sharing!

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.