在 woocommerce 中,我尝试使用以下方式检查特定产品类别的购物车项目:
add_action('woocommerce_before_cart', 'fs_check_category_in_cart');
function fs_check_category_in_cart() {
// Set $cat_in_cart to false
$cat_in_cart = false;
// Loop through all products in the Cart
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product = $cart_item['data'];
echo '<pre>',print_r($product),'</pre>';
// If Cart has category "download", set $cat_in_cart to true
if ( has_term( 'downloads', 'product_cat', $product->get_id() ) ) {
$cat_in_cart = true;
break;
}
}
// Do something if category "download" is in the Cart
if ( $cat_in_cart ) {
// For example, print a notice
wc_print_notice( 'Category Downloads is in the Cart!', 'notice' );
// Or maybe run your own function...
// ..........
}
}
我一直无法实现它。当我 print_r( $product )
时进一步检查
数组的末尾看起来像:
[current_class_name:WC_Data_Store:private] => WC_Product_Data_Store_CPT
[object_type:WC_Data_Store:private] => product-simple
)
[meta_data:protected] =>
)
1
数组末尾的这个 1 将其自身附加到我尝试引用的任何变量。所以我得到了
downloads1
如果有人知道这个数字可能来自哪里,它让我感到压力很大!
仅作记录,还执行 print_r( $woocommerce )
在数组末尾有 1。
感谢任何帮助。
最佳答案
使用 WordPress 检查购物车项目中的产品类别 has_term()
条件函数,您也需要使用 $cart_item['product_id']
来处理检查产品变体中的产品类别。
这样它会检查产品类别的父变量产品,因为产品变体类型不处理任何自定义分类。所以现在它适用于所有情况。
因此您重新访问的代码将是:
add_action('woocommerce_before_cart', 'check_product_category_in_cart');
function check_product_category_in_cart() {
// HERE set your product categories in the array (can be IDs, slugs or names)
$categories = array('downloads');
$found = false; // Initializing
// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item ) {
// If product categories is found
if ( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ) {
$found = true; // Set to true
break; // Stop the loop
}
}
// If any defined product category is found, we display a notice
if ( $found ) {
wc_print_notice( __('Product Category "Downloads" is in Cart items!'), 'notice' );
}
}
代码进入事件子主题(或事件主题)的 function.php 文件。经过测试并有效。
关于php - 在 Woocommerce 中检查产品类别的购物车项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51136303/