如果购物车中的任何商品来自特定类别,我需要能够有条件地将产品的 one 添加到WooCommerce订单/购物车 . 这是我尝试的代码,但它锁定了结帐和购物车页面,返回没有woocommerce信息,或之后的任何内容(没有页脚,没有其他页面元素等等......直到前面的WooCommerce数据 - 结束后,有一个很大的空白) . 如果有人能指出我正确的方向,那将是非常感谢!
这是我在functions.php文件中的内容:
/**
* Checks the cart to verify whether or not a product from a Category is in the cart
* @param $category Accepts the Product Category Name, ID, Slug or array of them
* @return bool
*/
function qualifies_basedon_product_category( $category ) {
foreach( WC()->cart->cart_contents as $key => $product_in_cart ) {
if( has_term( $category, 'fee', get_id_from_product( $product_in_cart, false ) ) ) {
return true;
}
}
// Return false in case anything fails
return false;
}
/**
* Adds a specific product to the cart
* @param $product_id Product to be added to the cart
*/
function add_incentive_to_cart( $product_id ) {
// Check the cart for this product
$cart_id = WC()->cart->generate_cart_id( $product_id );
$prod_in_cart = WC()->cart->find_product_in_cart( $cart_id );
// Add the product only if it's not in the cart already
if( ! $prod_in_cart ) {
WC()->cart->add_to_cart( $product_id );
}
}
add_action( 'woocommerce_check_cart_items', 'qualifies_for_incentive' );
function qualifies_for_incentive() {
// Incentive product
$incentive_product_id = 506;
if( qualifies_basedon_product_category( 'fee' ) ) {
add_incentive_to_cart( $incentive_product_id );
}
}
2 回答
你可以调查以下代码 -
希望这可能对你有所帮助 .
把它放在你的functions.php中:
我修改了现有代码中的代码,这就是为什么spfee和spfeeperprod仍在那里,但你并不真正需要它们,这就是为什么我把它们设置为0.我注意到让这段代码工作的缺点是这部分:
这将检查您要添加的项目的产品ID,该产品ID指定为“$ product_id” . 希望这会有所帮助(我昨天与它斗争了很多,但今天早上终于有了突破!)