Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
837 views
in Technique[技术] by (71.8m points)

php - Make WC_Cart add_to_cart method working for guests in Woocommerce

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.

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!

Here is my code:

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ); 
}

Code goes in functions.php file of your active child theme (or active theme). It should works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...