2013-03-08 182 views
20

對於我的WC產品頁面,我需要向body標籤添加一個類,以便我可以執行一些自定義樣式。以下是我爲此創建的功能...WooCommerce - 獲取產品頁面的類別

function my_add_woo_cat_class($classes) { 

    $wooCatIdForThisProduct = "?????"; //help! 

    // add 'class-name' to the $classes array 
    $classes[] = 'my-woo-cat-id-' . $wooCatIdForThisProduct; 
    // return the $classes array 
    return $classes; 
} 

//If we're showing a WC product page 
if (is_product()) { 
    // Add specific CSS class by filter 
    add_filter('body_class','my_add_woo_cat_class'); 
} 

...但是,如何獲取WooCommerce貓ID?

回答

52

WC產品可能不屬於一個或多個WC類別。假設你只想獲得一個WC類別ID。

global $post; 
$terms = get_the_terms($post->ID, 'product_cat'); 
foreach ($terms as $term) { 
    $product_cat_id = $term->term_id; 
    break; 
} 

請查看WooCommerce插件的「templates/single-product /」文件夾中的meta.php文件。

<?php echo $product->get_categories(', ', '<span class="posted_in">' . _n('Category:', 'Categories:', sizeof(get_the_terms($post->ID, 'product_cat')), 'woocommerce') . ' ', '.</span>'); ?> 
+0

剛剛將此代碼添加到「price.php」,並訪問單個產品頁面時,我收到以下錯誤消息:警告:爲foreach()提供的無效參數。我做錯了什麼,或者這個代碼與當前WC版本不兼容? – drake035 2015-01-03 21:58:33

+0

有沒有辦法用這個排除某些類別? – JacobTheDev 2015-03-02 22:00:18

+0

這幫助我獲得產品中斷,並在保存新評論後使用它重定向到類別列表。這是我的問題,如果有任何幫助。 http://stackoverflow.com/questions/42014311/wordpress-get-the-category-returns-empty – 2017-02-03 04:43:42

0

謝謝。我使用的是MyStile主題,我需要在搜索結果頁面顯示產品類別名稱。我將這個功能添加到我的孩子主題functions.php

希望它可以幫助別人。

/* Post Meta */ 


if (!function_exists('woo_post_meta')) { 
    function woo_post_meta() { 
     global $woo_options; 
     global $post; 

     $terms = get_the_terms($post->ID, 'product_cat'); 
     foreach ($terms as $term) { 
      $product_cat = $term->name; 
      break; 
     } 

?> 
<aside class="post-meta"> 
    <ul> 
     <li class="post-category"> 
      <?php the_category(', ', $post->ID) ?> 
         <?php echo $product_cat; ?> 

     </li> 
     <?php the_tags('<li class="tags">', ', ', '</li>'); ?> 
     <?php if (isset($woo_options['woo_post_content']) && $woo_options['woo_post_content'] == 'excerpt') { ?> 
      <li class="comments"><?php comments_popup_link(__('Leave a comment', 'woothemes'), __('1 Comment', 'woothemes'), __('% Comments', 'woothemes')); ?></li> 
     <?php } ?> 
     <?php edit_post_link(__('Edit', 'woothemes'), '<li class="edit">', '</li>'); ?> 
    </ul> 
</aside> 
<?php 
    } 
} 


?> 
2

我簡直出條紋從位於woocommerce文件夾在我的主題目錄中的內容,單popup.php這行代碼。

global $product; 
echo $product->get_categories(', ', ' ' . _n(' ', ' ', $cat_count, 'woocommerce') . ' ', ' '); 

由於我正在處理的主題已將woocommerce集成到其中,所以這是我的解決方案。

+0

謝謝你,它返回類別名稱,如何獲得類別id,而不是它的名字? – DigitCart 2016-07-14 13:37:59

相關問題