[英]Auto add a Product to Cart in Woocommerce 3
我希望任何訪問我的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
鈎在這里是不正確的,因此不能用於此…
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.