我希望任何访问我的Woocommerce商店的人都能在他的购物车中找到免费的产品。我找到了这段代码,它可以正常工作,但是它在日志中显示了许多php错误。
您是否知道为什么不干净?
请对此提供任何帮助。
/*
* AUTOMATICALLY ADD A PRODUCT TO CART ON VISIT
*/
function aaptc_add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 99999; // Product Id of the free product which will get added to cart
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
add_action( 'init', 'aaptc_add_product_to_cart' );
再次答复后进行编辑谢谢,您的代码没有更多错误,但是您可以检查是否可以选择基于SKU“惊喜”的免费产品吗?再次感谢大家。
function sku2id( $sku = false ) {
global $wpdb;
if( !$sku )
return null;
$product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku ) );
if ( $product_id )
return $product_id;
return null;
}
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 = sku2id("Surprise"); // FREE PRODUCT MUST HAVE SKU Surprise
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 );
}
}
请尝试使用template_redirect操作钩子重新尝试以下类似代码:
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
钩子不正确,因此不能用于…
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句