【问题标题】:Exclude a product category from the loop in Woocommerce从 Woocommerce 的循环中排除产品类别
【发布时间】:2019-02-06 08:06:21
【问题描述】:

我想从循环中排除我当前帖子的类别。通常很容易,这次它不起作用,我无法弄清楚这里出了什么问题。

这是我的页面代码:

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

 ?>

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

你有什么建议吗?

【问题讨论】:

    标签: php wordpress woocommerce custom-taxonomy


    【解决方案1】:

    您可以使用get_the_category 获取当前帖子的类别 并且您可以在参数中使用 category__not_in 排除类别。 所以你的论点应该像下面这样

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

    试试这个然后告诉我结果。谢谢

    【讨论】:

    • 这是我之前尝试过的解决方案,但它不起作用 - 即使这应该可以完成工作。我还是不明白为什么
    • 可能是因为某个产品类别不是正常类别?不确定
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 2018-05-17
      • 2018-05-18
      • 2019-08-05
      • 2018-11-09
      • 2013-08-11
      • 1970-01-01
      • 2018-09-06
      • 2018-12-19
      相关资源
      最近更新 更多