In WooCommerce, I'm using a script to show a number of random products but now I need to exclude one product category which I don't need to appear in this section.
How this can be done in my code?
My code:
<?php
global $product;
$args = array(
'posts_per_page' => 4,
'orderby' => 'rand',
'post_type' => 'product'
);
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<li class="single_product_lower_widget" style="list-style:none;">
<a href="<?php the_permalink(); ?>">
<span class="single_product_lower_widget_image">
<?php the_post_thumbnail() ?>
<span class="product-title"><?php the_title(); ?></span>
</span>
<p><?php get_post_meta( $post->ID, '_price', true ); ?></p>
</a>
</li>
<?php
endforeach;
wp_reset_postdata();
?>
You need to use a 'tax_query'
(defining the unwanted product category) this way:
<?php
// Set HERE your product category (to be excluded)
$category_slug = 'music' ;
$random_products = get_posts( array(
'posts_per_page' => 4,
'orderby' => 'rand',
'post_status' => 'publish',
'post_type' => 'product',
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category_slug,
'operator' => 'NOT IN',
))
));
foreach ( $random_products as $post ) : setup_postdata( $post );
?>
<li class="single_product_lower_widget" style="list-style:none;">
<a href="<?php the_permalink(); ?>">
<span class="single_product_lower_widget_image">
<?php the_post_thumbnail() ?>
<span class="product-title"><?php the_title(); ?></span>
</span>
<p><?php get_post_meta( $post->ID, '_price', true ); ?></p>
</a>
</li>
<?php
endforeach;
wp_reset_postdata();
?>
Tested and works
<?php
// Set HERE your product category (to be excluded)
$category_slug = 'music' ;
$random_products = get_posts( array(
'posts_per_page' => 4,
'orderby' => 'rand',
'post_status' => 'publish',
'post_type' => 'product',
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category_slug,
'operator' => 'NOT IN',
))
));
foreach ( $random_products as $post ) : setup_postdata( $post );
?>
<li class="single_product_lower_widget" style="list-style:none;">
<a href="<?php the_permalink(); ?>">
<span class="single_product_lower_widget_image">
<?php the_post_thumbnail() ?>
<span class="product-title"><?php the_title(); ?></span>
</span>
<p><?php get_post_meta( $post->ID, '_price', true ); ?></p>
</a>
</li>
<?php
endforeach;
wp_reset_postdata();
?>