从Woocommerce的循环中排除产品类别

问题描述 投票:1回答:2

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

这是我的页面代码:

$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
2个回答
1
投票

尝试使用以下额外的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; ?>

0
投票

您可以使用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
    );

试试这个然后让我知道结果。谢谢

© www.soinside.com 2019 - 2024. All rights reserved.