skip to Main Content

I have two custom post types, ‘product’ and ‘product_review’. The CPT ‘product_review’ has a taxonomy ‘product_name’ whose slug matches the CPT ‘product’

An example ‘Product A’ is the product post. ‘Product Review A’ is the product_review post that has a ‘product_name’ taxonomy value of ‘product_a’.

I need to show how many ‘product_review’ each ‘product’ has.

<?php
    global $post;
    $post_slug = $post->post_name;
    //echo $post_slug; 
    //this outputs the name of the product, which I need

    $terms = get_terms('product_review');
    foreach ( $terms as $post_slug ) {
    echo $term->count . 'Reviews';
?>

It doesn’t show any count. I want it to show how many $terms(how many reviews) are tied to $post_slug(name of product). The ‘product_review’ slug matches the slug of the product.

2

Answers


  1. Chosen as BEST ANSWER

    @mikerojas answer got me close, but wasn't returning accurate data. Here is what I came up with that got me what I needed.

    <?php
        $review_args = array(
                'post_type' => 'my_post_type',
                'post_status' => 'publish',
                'tax_query' => array(
                        array (
                                'taxonomy' => 'my_taxonomy',
                                'field' => 'slug',
                                //this is already inside a loop, making it dynamic to only grab the reviews whose tax value equals the post slut
                                'terms' => $post->post_name,
                        )
                ),
        );
        if($num = count( get_posts ( $review_args)) <= 1) {
                echo 'Review ' . $num = count( get_posts( $review_args ) );
        } else {
                echo 'Reviews ' . $num = count( get_posts( $review_args ) );
        }
                                                    
        wp_reset_postdata();
    ?>
    

  2. You can use a custom WP_Query and the found_posts prop like below:

    // example query args
    $args = [
        // look for reviews cpt
        'post_type' => 'product_review',
    
        // limit to posts that match our taxonomy product name
        'tax_query' => [
            [
                'taxonomy' => 'product_name',
                'field'    => 'slug',
                'terms'    => [ 'product_a' ]
            ]
        ]
    ];
    
    // run the query
    $query = new WP_Query( $args );
    
    // grab "total" found posts
    $total = $query->found_posts;
    
    // display the total
    echo $total
    
    // reset post data so we dont break the main loop
    wp_reset_postdata();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search