2016-08-13 128 views
2

這是關於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

回答

1

根據您的第一個代碼段,這應該工作,並會避免基於當前的產品類別相關的產品,以顯示您當前的產品。

這是代碼:

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

相關問題