![](/img/trans.png)
[英]Automatically add to cart latest published product on visit in Woocommerce
[英]Automatically add multiple products to cart on visit WooCommerce
我正在一個網上商店測試用例上工作,我想在訪問時將商品/產品自動添加到購物車中。 因此,當我到處遍地發現相同的代碼時,我便搜索了類似的內容。
/*
* goes in theme functions.php or a custom plugin
**/
// add item to cart on visit
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 64;
$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->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 );
}
}
}
從:
https://docs.woocommerce.com/document/automatically-add-product-to-cart-on-visit/ https://gist.github.com/kloon/2376300
因此,如果您只有一種產品,但是我想添加一種以上的產品,則此方法效果很好。 有沒有一些PHP知識(和一些WordPress)可以幫助我的人? 提前致謝!
實際上,至少有兩種方法可以執行此操作。 您可以多次調用add_to_cart
函數,也可以創建一個循環。 兩種方法都在這里:
方法1
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 64;
$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->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 );
WC()->cart->add_to_cart( $product_id2 );
WC()->cart->add_to_cart( $product_id3 );
WC()->cart->add_to_cart( $product_id4 );
}
}
}
方法二
foreach ($articles as $article) {
WC()->cart->add_to_cart( $article );
}
請注意,您應該創建一個名為articles
的新數組,其中包含所需產品的所有ID。 然后讓您煩惱的另一件事是檢查購物車是否容納超過0件物品,並檢查是否所有物品都在其中。
方法2看起來像這樣:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$articles = array(64);
$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 (($key = array_search($_product->id, $articles)) !== false)
unset($articles[$key]);
}
// if product not found, add it
if ( count($articles) > 0 ) {
foreach ($articles as $article) {
WC()->cart->add_to_cart($article);
}
}
} else {
// if no products in cart, add it
foreach ($articles as $article) {
WC()->cart->add_to_cart( $article );
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.