从Woocommerce循环中排除产品类别 [英] Exclude a product category from the loop in Woocommerce

查看:75
本文介绍了从Woocommerce循环中排除产品类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从循环中排除当前帖子的类别。通常很容易,这一次它不起作用,而且我不知道这里出了什么问题。

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.

这是我的页面代码:

$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>

页面结尾

 <?php 

wp_reset_postdata();

 ?>

它显示所有产品(显示的产品除外,这是正确的)。

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

您有任何建议吗?

推荐答案

尝试以下附加的 tax_query ,因为产品类别是自定义分类法:

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; ?>

这篇关于从Woocommerce循环中排除产品类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆