在有人将“ Variation”类别的产品添加到购物车后,我希望有一个不同的布局。
我有一个可以正常工作但破坏布局的代码。它会检查购物车中是否有某种类别的产品,如果有,它会在body_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;
}
如果我查看源代码,并且购物车中有商品“ 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文件中。经过测试和工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句