更新时间:2023-10-25 14:36:52
尝试而是使用template_redirect操作钩子重新访问了类似的代码:
Try instead this revisited similar code using template_redirect action hook:
add_action( 'template_redirect', 'auto_add_product_to_cart' );
function auto_add_product_to_cart() {
if ( is_admin() ) return;
// Product Id of the free product which will get added to cart;
$product_id = 99999;
if ( WC()->cart->is_empty() )
{
// No products in cart, we add it
WC()->cart->add_to_cart( $product_id );
}
else
{
$found = false;
//check if product already in cart
foreach ( WC()->cart->get_cart() as $cart_item ) {
if ( $cart_item['data']->get_id() == $product_id )
$found = true;
}
// if the product is not in cart, we add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
}
}
代码进入function.php文件您的活动子主题(或活动主题)。经过测试并有效。
注意:
init
钩在这里是不正确的,因此不能用于此……
Note: The
init
hook is not correct here and not to be used for this…