使WC_Cart add_to_cart方法为Woocommerce中的访客工作 [英] Make WC_Cart add_to_cart method working for guests in Woocommerce

查看:377
本文介绍了使WC_Cart add_to_cart方法为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.

在我的自定义插件中,我想向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

代码运行无错误.并且它以登录用户/admin的身份工作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中的访客工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆