Dirty Bird Design
Dirty Bird Design

Reputation: 5543

Display how many reviews there are for a CPT

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.

Upvotes: 0

Views: 61

Answers (2)

Dirty Bird Design
Dirty Bird Design

Reputation: 5543

@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();
?>

Upvotes: 0

mikerojas
mikerojas

Reputation: 2338

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

Upvotes: 1

Related Questions