Site logo

Archived topic

Show post counts with category name

6 replies · Started by Pankaj on January 14, 2023

Viewing posts 1–7 of 7

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

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

Hello,

This fixed what I was looking.

Regards

Glad to hear that!

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.

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

Thanks for sharing!

This archived topic is closed to new replies.