2016-01-27 35 views
1

我正在創建一個自定義插件,根據分配給產品的標籤獲取相關產品。我面臨一個問題。當我運行一個循環時,它給了我一個警告消息。我想檢查的是,如果特定產品有任何類別分配給它。我如何檢查是否有任何類別已分配到woocommerce產品。請幫幫我。提前致謝。如何檢查woocommerce產品是否有任何類別分配給它?

我的自定義代碼

while ($loop->have_posts()) : $loop->the_post(); 
    global $product; 
    global $post; 

    $feat_image = wp_get_attachment_url(get_post_thumbnail_id($loop->post->ID)); 
    $terms200 = get_the_terms($loop->post->ID, 'product_cat'); 


     // if(!empty($terms200) || $terms200!='' || $terms200!=null){ 
    if (get_category($loop->post->ID)->category_count != 0){   
     $content.='<li class="product-small grid1 grid-normal">'; 
      $content.='<div class="inner-wrap">'; 
       $content.='<a href="'.get_the_permalink($loop->post->ID).'">'; 
        $content.='<div class="product-image hover_fade_in_back">'; 
         $content.='<div class="front-image">'; 
          $content.='<img src="'.$feat_image.'" class="attachment-shop_catalog wp-post-image" style="width:247px !important;height:300px !important;" />'; 
         $content.='</div>'; 
        $content.='</div>'; 
       $content.='</a>'; 
       $content .='<div class="info style-grid1">'; 
        $content .='<div class="text-center">'; 
         $count=1; 
         foreach (@$terms200 as $term) { 
           if($count==1){ 
            $content.='<h5 class="category"><a href="'.get_site_url().'/?product_cat='.$term->slug.'" rel="tag">'.$term->name.'</a></h5>'; 
            $content.='<div class="tx-div small"></div>'; 
           } 
          $count++; 
         } 
         $content .='<a href="'.get_the_permalink($loop->post->ID).'"><p class="name">'.$loop->post->post_title.'</p></a>'; 
         if ($price_html = $product->get_price_html()) : 
         $content .='<span class="price"><span class="amount">'.$price_html.'</span></span>'; 
         endif; 
         $content.='<div class="mycustomcartbuttonbox">[add_to_cart id="'.$loop->post->ID.'"]</div>';         
        $content .='</div>'; 
       $content .='</div>'; 
      $content.='</div>'; 
     $content.='</li>'; 
     echo do_shortcode($content); 

    } 

endwhile; 

回答

6

它實際上是非常簡單的做到這一點。

只要輸入您的內循環:

if(!has_category("uncategorized")){ 
//do stuff 
} 

如果不工作,你可以嘗試:

if(!has_term('uncategorized', 'product_cat')){ 
    //do stuff 
} 

您可以在學習更多關於它:https://codex.wordpress.org/Function_Reference/has_category

+0

將這個與woocommerce類別一起工作? –

+0

@NitinJohnson我相信它會,我已經編輯我的帖子,如果它不工作的替代。 – Jeroen

+0

@NitinJohnson - 您需要爲WooCommerce使用has_term。 –

相關問題