在 WooCommerce 中添加与产品类别相关的正文 class
Add a body class related to the product category in WooCommerce
如何添加与产品类别 slug 相关的正文class?
谢谢!
在 Wordpress 支持网站上有一个很好的指南可以帮助您做到这一点:Modify body_class() output to show category-{slug} for single posts
我已经更改了 post 中的代码以满足您的需要:
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes, $class) {
if (is_single() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
echo $category->cat_name . ' ';
// add category slug to the $classes array
$classes[] = $category->slug;
}
}
// return the $classes array
return $classes;
}
将此添加到您的 functions.php
add_filter( 'body_class', 'wc_cat_names' );
function wc_cat_names( $classes ) {
if(is_product()){
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$classes[] = $term->slug;
}
}
return $classes;
}
这个只能在 woocommerce 产品页面上使用,是的,我在我的测试网站上测试了这个。
如何添加与产品类别 slug 相关的正文class?
谢谢!
在 Wordpress 支持网站上有一个很好的指南可以帮助您做到这一点:Modify body_class() output to show category-{slug} for single posts
我已经更改了 post 中的代码以满足您的需要:
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes, $class) {
if (is_single() ) {
global $post;
foreach((get_the_category($post->ID)) as $category) {
echo $category->cat_name . ' ';
// add category slug to the $classes array
$classes[] = $category->slug;
}
}
// return the $classes array
return $classes;
}
将此添加到您的 functions.php
add_filter( 'body_class', 'wc_cat_names' );
function wc_cat_names( $classes ) {
if(is_product()){
global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$classes[] = $term->slug;
}
}
return $classes;
}
这个只能在 woocommerce 产品页面上使用,是的,我在我的测试网站上测试了这个。