I am working on a product page where I show reviews from my post type ‘reviews’, if the product page title matches with my term from the taxonomy ‘review-product’.
Example.
Product page title: Refrigerator
Show (reviews) posts with:
- Post type: ‘reviews’
- Taxonomy: ‘review-product’
- Term: Refrigerator
This works totally fine. But sometimes I have no reviews for a product (because there is no match between product title and term) and then I want to show ‘General’ reviews. In my website these are posts with:
- Post type: ‘reviews’
- Taxonomy: ‘review-product’
- Term: No term (!!!)
This posts don’t have a term from the taxonomy ‘review-product’.
My Question:
How can I show reviews posts without a term, if there are no reviews posts matching the product title.
This is what I have now:
function gtp_show_reviews( $number = 100, $term = null ) {
$reviews = new WP_Query( array(
'post_type' => 'reviews',
'review-product' => $term, // Fill this with product page slug (refrigerator)
));
if( $reviews->have_posts() ) {
while( $reviews->have_posts() ) {
$reviews->the_post();
// The review
}
}
else {
// Here I try to unset the 'review-product' term
unset($reviews->query_vars['review-product']);
unset($reviews->query_vars['term']);
while( $reviews->have_posts() ) {
$reviews->the_post();
// Check if review has no term
if( $reviews->has_term() == false ) {
// The review
}
}
}
wp_reset_postdata();
}
2 s
You cannot use the same object of WP_Query
twice. Therefore you need to create another one with a tax_query
parameter to fetch posts which are not assigned to any term.
//fetch all reviews which have no assigned term in 'review-product'
$taxonomy = 'review-product';
$post_type="reviews";
$args = [
'post_type' => $post_type,
'tax_query' => [
[
'taxonomy' => $taxonomy,
'terms' => get_terms( $taxonomy, [ 'fields' => 'ids' ] ),
'operator' => 'NOT IN'
]
]
];
$query = new \WP_Query( $args );
The idea is to fetch a list of all terms of your taxonomy and pass them as argument to your tax-query with the NOT IN
operator.
The second loop in your example should walk over the new WP_Query
object.