为 WooCommerce 购物车项目的特定产品类别添加正文 class
Add a body class for a specific product category on WooCommerce cart items
有人将类别 "Variation" 的产品添加到购物车后,我想要不同的布局。
我的代码运行良好,但破坏了布局。它会查看某个类别的产品是否在购物车中,如果是,它会在 body_class
中添加一个 class
/* ADD PRODUCT CLASS TO BODYCLASS */
add_filter( 'body_class', 'prod_class_to_body_class' );
function prod_class_to_body_class() {
// set flag
$cat_check = false;
// check cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
if ( has_term( 'my_product_cat', 'product_cat', $product->id ) ) {
$cat_check = true;
break;
}
}
// if a product in the cart has the category "my_product_cat", add "my_class" to body_class
if ( $cat_check ) {
$classes[] = 'my_class';
}
return $classes;
}
如果我查看源代码,我可以看到新的 class,如果我的购物车中有类别 'my_product_cat' 的产品。但布局是一场灾难。
有人看错了吗?
有多个错误:
- 缺少主函数变量参数
- 对于
has_term()
在购物车中的使用,请始终使用 $cart_item['product_id']
以使其适用于产品变体项目。
您的代码也可以简化。请尝试以下操作:
// ADD PRODUCT CLASS TO BODYCLASS
add_filter( 'body_class', 'prod_class_to_body_class' );
function prod_class_to_body_class( $classes ) {
$check_cat = 'my_product_cat'; // Product category term to check
$new_class = 'my_class'; // Class to be added
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Check for a product category term
if ( has_term( $check_cat, 'product_cat', $cart_item['product_id'] ) ) {
$classes[] = $new_class; // Add the new class
break; // Stop the loop
}
}
return $classes;
}
代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。
有人将类别 "Variation" 的产品添加到购物车后,我想要不同的布局。
我的代码运行良好,但破坏了布局。它会查看某个类别的产品是否在购物车中,如果是,它会在 body_class
中添加一个 class/* ADD PRODUCT CLASS TO BODYCLASS */
add_filter( 'body_class', 'prod_class_to_body_class' );
function prod_class_to_body_class() {
// set flag
$cat_check = false;
// check cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
if ( has_term( 'my_product_cat', 'product_cat', $product->id ) ) {
$cat_check = true;
break;
}
}
// if a product in the cart has the category "my_product_cat", add "my_class" to body_class
if ( $cat_check ) {
$classes[] = 'my_class';
}
return $classes;
}
如果我查看源代码,我可以看到新的 class,如果我的购物车中有类别 'my_product_cat' 的产品。但布局是一场灾难。
有人看错了吗?
有多个错误:
- 缺少主函数变量参数
- 对于
has_term()
在购物车中的使用,请始终使用$cart_item['product_id']
以使其适用于产品变体项目。
您的代码也可以简化。请尝试以下操作:
// ADD PRODUCT CLASS TO BODYCLASS
add_filter( 'body_class', 'prod_class_to_body_class' );
function prod_class_to_body_class( $classes ) {
$check_cat = 'my_product_cat'; // Product category term to check
$new_class = 'my_class'; // Class to be added
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// Check for a product category term
if ( has_term( $check_cat, 'product_cat', $cart_item['product_id'] ) ) {
$classes[] = $new_class; // Add the new class
break; // Stop the loop
}
}
return $classes;
}
代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。