WooCommerce - 获取产品页面的类别
问题描述:
对于我的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?
答
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>'); ?>
答
谢谢。我使用的是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
}
}
?>
答
我简直出条纹从位于woocommerce文件夹在我的主题目录中的内容,单popup.php这行代码。
global $product;
echo $product->get_categories(', ', ' ' . _n(' ', ' ', $cat_count, 'woocommerce') . ' ', ' ');
由于我正在处理的主题已将woocommerce集成到其中,所以这是我的解决方案。
+0
谢谢你,它返回类别名称,如何获得类别id,而不是它的名字? – DigitCart 2016-07-14 13:37:59
刚刚将此代码添加到“price.php”,并访问单个产品页面时,我收到以下错误消息:警告:为foreach()提供的无效参数。我做错了什么,或者这个代码与当前WC版本不兼容? – drake035 2015-01-03 21:58:33
有没有办法用这个排除某些类别? – JacobTheDev 2015-03-02 22:00:18
这帮助我获得产品中断,并在保存新评论后使用它重定向到类别列表。这是我的问题,如果有任何帮助。 http://stackoverflow.com/questions/42014311/wordpress-get-the-category-returns-empty – 2017-02-03 04:43:42