Support

Account

Home Forums General Issues Show number of posts with specific value within a category

Solved

Show number of posts with specific value within a category

  • What I have:
    – A Custom Post Type called ‘Recipes’
    – A Hierarchical Custom Taxonomy ‘Desserts > Chocolate, Cakes, etc.’
    – A ACF selector field with the difficulty level ‘Easy, Average, Difficult’
    – I’m showing a table in the archives-recipes.php, which looks like this:

    ————————————————————-
    Easy Average Difficult
    ————————————————————-
    Desserts
    ————————————————————-
    Cakes 2 1
    ————————————————————-
    Post 1 Go
    ————————————————————-
    Post 2 Go
    ————————————————————-
    Post 3 Go

    I need to know how to show the number of custom posts with the same value inside a custom sub-category.
    Any idea?

    Thanks for your help 🙂

    Irene

  • You can use get_terms, then term->count..

    The below will list all the terms from the Desserts taxonomy with their name and post count.

    <?php   
    $terms = get_terms( 'desserts' );
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
        echo '<ul>';
        foreach ( $terms as $term ) {
            echo '<li>' . $term->name . ' - ' . $term->count . '</li>';
        }
        echo '</ul>';
    }
    ?>
    

    For more info check – HERE

  • Sorry just re-read your question. You need to get the number of posts with a difficulty of Easy, Average & Difficult for each term right?

    You’ll need a custom wp_query with a tax_query and a meta_query.. Something like the below will get you the post count for Easy Chocolate Deserts..

    
    $args = array(
    	'post_type'  => 'recipes',
    	'tax_query' => array(
    		array(
    			'taxonomy' => 'desserts',
    			'field'    => 'slug',
    			'terms'    => 'chocolate',
    		),
    	),
    	'meta_query' => array(
    		array(
    			'key'     => 'difficulty',
    			'value'   => 'Easy',
    			'compare' => 'IN',
    		),
    	),
    );
    $easy_choc_query = new WP_Query( $args );
    
    echo $easy_choc_query->found_posts;
    

    More info from the Codex

    To make it more dynamic we’d need to see your html structure. You’d possibly need to put something like the above inside the get_terms foreach loop, swapping out ‘chocolate’ and ‘easy’ for variables that changed with each iteration.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Show number of posts with specific value within a category’ is closed to new replies.