WooCommerce - 获取产品页面的类别 [英] WooCommerce - get category for product page
本文介绍了WooCommerce - 获取产品页面的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于我的 WC 产品页面,我需要向 body 标签添加一个类,以便我可以执行一些自定义样式.这是我为此创建的函数...
For my WC product pages, I need to add a class to the body tag so that I can perform some custom styling. Here's the function I'm creating for this...
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 cat ID?
...but how do I get the WooCommerce cat ID?
推荐答案
一个 WC 产品可能不属于一个、一个或多个 WC 类别.假设您只想获得一个 WC 类别 ID.
A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category 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 文件.
Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>
这篇关于WooCommerce - 获取产品页面的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文