简体   繁体   中英

Wordpress related products loop hide current product

I am displaying latest products when viewing a certain product. When viewing the product it still appears as a "Recent product" at the bottom.

<ul class="products">
                <?php
                $args = array(
                    'post_type' => 'product',
                    'posts_per_page' => 3,
                    'post__in' => $related,
                );
                $loop = new WP_Query( $args );
                if ( $loop->have_posts() ) {
                    while ( $loop->have_posts() ) : $loop->the_post();
                    wc_get_template_part( 'content', 'product' );
                    endwhile;
                } else {
                    echo __( 'No products found' );
                }
                wp_reset_postdata();
                ?>

I tried using 'post__not_in' => array($product->id) , but it doesn't work.

How do I hide the product I am viewing from the recent products loop?

You forgot to declare $product as global but both of global $post; $post->ID global $post; $post->ID and global $product; $product->id global $product; $product->id will work. Also, note about post__not_in

If this is used in the same query as post__in, it will be ignored

You will need to remove your current product id from $related if it's there (and I assume it is) like so

$key=array_search($post->ID,$related);
//or
$key=array_search($product->id, $related);
if($key!==FALSE)
{
    unset($related[$key]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM