2017-09-06 153 views
1

我的網站上有產品列表,每個產品都有自己的標籤。我試圖在結帳頁面上顯示此標籤。我編寫了一個代碼,但它顯示了我所有產品的所有標籤,不僅僅是購物車中的標籤。 這裏是我的代碼:Wordpress + WooCommerce獲取產品標籤

 global $woocommerce; 
    $items = $woocommerce->cart->get_cart(); 
    foreach($items as $item => $values) { 
     $_product = wc_get_product($values['data']->get_id()); 
     echo "<b>".$_product->get_title().'</b> <br> Quantity: '.$values['quantity'].'<br>'; 
     $price = wp_get_post_tags($values['product_id'] , '_tag_ids', true); 
     echo " Price: ".$price."<br>"; 


       $terms = get_terms('product_tag'); 
     $term_array = array(); 
     if (! empty($terms) && ! is_wp_error($terms)){ 
      foreach ($terms as $term) { 
       $term_array[] = $term->name; 
      } 

    } 


     print_r($values['product_id']); 

     print_r($term_array); 

     if(in_array('black',$term_array)) { 
     echo 'hello exists'; 
     } else { 
     echo 'not exists'; 
     } 

    } 
    } 

所以它的顯示正確=「你好存在」,但它的顯示,因爲它是從所有產品把所有標籤。我如何通過產品ID獲取標籤?我將我的產品ID存儲在$values['product_id'] 我試過get_terms($values['product_id'], 'product_tag');但它沒有奏效!

回答

3

您需要使用get_the_terms,不get_terms

$terms = get_the_terms(get_the_ID(), 'product_tag'); 
+1

謝謝! '$ terms = get_the_terms($ values ['product_id'],'product_tag');'爲我工作:) –

+1

這是一個很好的答案,只要使用get_the_ID()而不是the_ID()如果你不想要這篇文章ID呼應:) –

+0

謝謝,@PavelPetrov你是對的,我會更新我的答案,愚蠢的錯誤在我的部分。 – admcfajn

相關問題