单一产品页面 - 从相关产品中排除当前产品

问题描述:

这是关于WooCommerce单一产品页面。我试图使用产品类别来显示相关产品。我可以用下面的代码来显示它。使用这将包括当前的文章,它只显示产品。单一产品页面 - 从相关产品中排除当前产品

<?php 
    global $post; 
     $terms = get_the_terms($post->ID, 'product_cat');  
     foreach ($terms as $term ) {   
      $product_cat_name = $term->name; 
      break; 
     }   
    $ids = array(); 

    $currentID = get_the_ID(); 

    $args = array('post_type' => 'product', 'product_cat' => $product_cat_name);  
    $loop = new WP_Query($args); 
    while ($loop->have_posts()) : $loop->the_post(); global $product; 
     $ids[] = $loop->post->ID; 
    endwhile; 
    wp_reset_query(); 

    print_r($ids); 
?> 

但我试图阻止当前产品在相关产品上显示。我尝试使用下面的代码的第一秒,但不排除它,它检索所有默认帖子。

<?php 
    global $post; 
     $terms = get_the_terms($post->ID, 'product_cat');  
     foreach ($terms as $term ) {   
      $product_cat_name = $term->name; 
      break; 
     }   
    $ids = array();  

    $currentID = get_the_ID(); 

    $args = array('post_type' => 'product', 'product_cat' => $product_cat_name, 'post__not_in' => array($currentID));  
    $loop = new WP_Query($args); 
    while ($loop->have_posts()) : $loop->the_post(); global $product; 
     $ids[] = $loop->post->ID; 
    endwhile; 
    wp_reset_query(); 

    print_r($ids); 
?> 

我该如何做到这一点?

感谢

+0

好吧,我有一个功能为你解答...它应该工作。我在我的代码中删除了全局$ product;在这里不需要。请尝试并告诉我。 – LoicTheAztec

根据您的第一个代码段,这应该工作,并会避免基于当前的产品类别相关的产品,以显示您当前的产品。

这是代码:

<?php 

global $post; 

$ids = array(); 

// Get the "main" product category 
$terms = get_the_terms($post->ID, 'product_cat'); 
foreach ($terms as $term){ 
    if($term->parent != 0) { 
     $product_cat_name = $term->name; 
     break; // stop the loop 
    } 
// The Query  
$loop = new WP_Query(array(
    'post_type' => 'product', 
    'product_cat' => $product_cat_name, 
    'post__not_in' => array($post->ID) // Avoid displaying current product 
)); 

if ($loop->have_posts()): 
    while ($loop->have_posts()) : $loop->the_post(); 
     $ids[] = $loop->post->ID; // Set all other product IDs for that product category 
    endwhile; 
endif; 

wp_reset_query(); 

// Raw output 
print_r($ids); 

?> 

这应该工作...

+0

这没有为我工作。 :/它给最新的woocommerce错误。 – GauchoCode

+0

@GauchoCode ...我已经测试,更新并优化了我的答案代码。如果你喜欢,试试看。谢谢(对不起......有一个丢失的括号错误) – LoicTheAztec