沃梦达 / 编程问答 / php问题 / 正文

使 WC_Cart add_to_cart 方法为 Woocommerce 中的客人工作

Make WC_Cart add_to_cart method working for guests in Woocommerce(使 WC_Cart add_to_cart 方法为 Woocommerce 中的客人工作)

本文介绍了使 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

代码运行没有错误.它以登录用户/管理员身份 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 中的客人工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使 WC_Cart add_to_cart 方法为 Woocommerce 中的客人工作

基础教程推荐