問題描述
我正在嘗試讓我的代碼工作.現在搜索小時.我發現了類似的問題,例如 這個.但不幸的是,似乎沒有人找到解決辦法.
Im trying to get my code to work. Searching for hours now. I found similar questions like this one. But unfortunately noone seems to find a solution.
在我的自定義插件中,我想將特定項目添加到 WC 購物車并將用戶直接重定向到結帳.作為登錄用戶,它就像一個魅力,但對于客人來說,它在結賬時顯示一個空白頁面(woocommerce_checkout 簡碼在這種情況下似乎沒有返回任何內容).所以我想出了一個檢查,如果購物車是空的.顯然是因為購物車頁面"顯示購物車中還沒有商品".
In my custom plugin I want to add a specific item to the WC cart and redirect the user directly to the checkout. As a logged in user it works like a charm but for guests it shows a blank page on checkout (woocommerce_checkout shortcode seems to return nothing in this case). So I came up with a check if the cart iss till empty. Apparently it is because the "cart-page" shows "There are no items in the cart yet".
在代碼中,我檢查購物車是否仍然是空的,但它告訴我不是!
In code i check if the cart is still empty but it tells me its not!
這是我的代碼:
if(!$wooID = $wpdb->get_var("SELECT wooID FROM ".$wpdb->prefix."ceb_events WHERE id = $event")) die("ERROR GETTING WOOID");
WC()->cart->empty_cart();
if(!WC()->cart->add_to_cart( $wooID, 1 )) die("CART GOT NOT UPDATED. THERE IS AN ERROR 1.");
if(WC()->cart->get_cart_contents_count() == 0) die("CART GOT NOT UPDATED. THERE IS AN ERROR 2.");
//Here follows the redirect to checkout page
代碼運行沒有錯誤.它以登錄用戶/管理員身份 100% 工作.只是不是作為客人,即使我允許在 woocommerce 設置中進行客人結帳.
The code runs without errors. And it works 100% as a logged in user / admin. Just not as guest, even tho I allowed the guest checkout in the woocommerce settings.
推薦答案
您需要在未登錄的情況下啟動 Woocommerce User 會話.因此您將使用以下內容:
You need to initiate Woocommerce User session when it's not logged in. So you will use the following:
add_action( 'woocommerce_init', 'force_non_logged_user_wc_session' );
function force_non_logged_user_wc_session(){
if( is_user_logged_in() || is_admin() )
return;
if ( isset(WC()->session) && ! WC()->session->has_session() )
WC()->session->set_customer_session_cookie( true );
}
代碼位于活動子主題(或活動主題)的 functions.php 文件中.它應該有效.
Code goes in functions.php file of your active child theme (or active theme). It should works.
這篇關于使 WC_Cart add_to_cart 方法為 Woocommerce 中的客人工作的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!