[SOLVED] Is there any ways to count posts in categories?

Issue

I have nearly 500 categories in my web site. I want to add a function to count posts in each category. Since the categories are too many, i can’t try to add posts id or name to each category code. I need wordpress to do it automatically for each category. Is there any way you can show me to do that?

{

                    <a href="<?php echo $collection_link; ?>">
                        <h5 class="text-center card-title">
                            <?php the_category(); ?>
                        </h5>
                    </a>
                    <a href="<?php echo $collection_link; ?>">
                        <p class="text-center d-flex justify-content-center card-text">
                            <?php //this is where post count should be displayed ?>
                        </p>
                    </a>

                </div><!-- end card-body -->}

Solution

if you are using the default categories, then you may try this:

 $categories = get_the_category();

if ( ! empty( $categories ) ) {
    foreach( $categories as $cat ){
        echo $cat->name . " " . $cat->count;
    }   
}

$Categories will be an array of cat objects. So if it’s no empty then you’ll be able to access to each cat and retrieve it’s props.

Answered By – Gabriel Dzul

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *