Exclude a product category from the loop in Woocommerce

跟風遠走 提交于 2020-07-30 10:19:07

问题


I'd like to exclude the category of my current post from the loop. Pretty easy usually, this time it doesn't work and I can't figure out what's wrong here.

Here's my page'code:

$postid = get_the_ID(); // curret product ID

<section class="related products">

            <?php
            $args = array(
            'post__not_in'          => array($postid), // Exclude displayed product
            'post_type'             => 'product',
            'post_status'           => 'publish',
            'posts_per_page'        => '6',
            'cat'                   => '-33' // Exclude cat


        );

    $related_products = new WP_Query($args);

    ?>  


    <h2><?php esc_html_e( 'Related products' ); ?></h2>



           <div class="owl-carousel rigid-owl-carousel" >


                    <?php if( $related_products->have_posts() ) {

                     while( $related_products->have_posts() ) : $related_products->the_post(); 


                    wc_get_template_part( 'content', 'product' ); 


                     endwhile; }



                    ?>



</section>

End of page

 <?php 

wp_reset_postdata();

 ?>

It shows all products (except the displayed one, which is correct).

Do you have any suggestion?


回答1:


Try with the following additional tax_query, as product categories are a custom taxonomy:

<?php
$related_products = new WP_Query( array(
    'post__not_in'          => array( get_the_ID() ), // Exclude displayed product
    'post_type'             => 'product',
    'post_status'           => 'publish',
    'posts_per_page'        => '6',
    'tax_query' => array( array(
        'taxonomy' => 'product_cat',
        'field' => 'id',
        'terms' => array( 33 ), // HERE the product category to exclude
        'operator' => 'NOT IN',
    ) ),
) );

if( $related_products->have_posts() ) : ?>

<h2><?php esc_html_e( 'Related products' ); ?></h2>
<div class="owl-carousel rigid-owl-carousel" >
<?php 
while( $related_products->have_posts() ) : $related_products->the_post(); 
    wc_get_template_part( 'content', 'product' ); 
endwhile;
wp_reset_postdata();
?>
</div>
<?php endif; ?>



回答2:


You can get current post's category using get_the_category and you can exclude categories using category__not_in in your argument. So your argument should be like bellow

    $args = array(
        'post__not_in'          => array($postid), // Exclude displayed product
        'post_type'             => 'product',
        'post_status'           => 'publish',
        'posts_per_page'        => '6',
        'category__not_in'      => get_the_category(get_the_ID())//exclude category of current post
    );

Try this then let me know the result. Thanks



来源:https://stackoverflow.com/questions/52112936/exclude-a-product-category-from-the-loop-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!