【发布时间】:2021-08-30 13:24:46
【问题描述】:
我正在创建一个 woocommerce 功能,允许我根据以下条件将特定产品添加到购物车:
-
特定类别
-
产品的总成本高于我定义的值 在 $ min_price
我能够根据类别获得,woocommerce 添加指定的产品。 不幸的是,当产品的总价值高于 $ min_price 时,我无法描述执行此操作的流程。
谁能帮助我?谢谢
add_action( 'woocommerce_before_calculate_totals', 'auto_add_item_based_on_product_category', 10, 1 );
function auto_add_item_based_on_product_category( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$min_price = 77.47; // The minimal cart amount
$required_categories = array('computer-based', 'esami-paper-based'); // Required product category(ies)
$added_product_id = 5065; // Specific product to be added automatically
$matched_category = false;
$matched_subtotal = false;
// Loop through cart items
foreach ( $cart->get_cart() as $item_key => $item ) {
// Check for product category
if( has_term( $required_categories, 'product_cat', $item['product_id'] ) ) {
$matched_category = true;
}
// Check if specific product is already auto added
if( $item['data']->get_id() == $added_product_id ) {
$saved_item_key = $item_key; // keep cart item key
}
// Check it the minimum subtotal is reached
if ( !empty( $product_subtotal > $min_price ) ) {
$matched_subtotal = true;
}
}
// If specific product is already auto added but without items from product category and minimun subtotal is not reached
if ( isset($saved_item_key) && ! $matched_category && ! $matched_subtotal ) {
$cart->remove_cart_item( $saved_item_key ); // Remove specific product
}
// If there is an item from defined product category and subtotal reached and specific product is not in cart
elseif ( ! isset($saved_item_key) && $matched_category && $matched_subtotal ) {
$cart->add_to_cart( $added_product_id ); // Add specific product
}
}
【问题讨论】:
标签: php woocommerce hook-woocommerce