WooCommerce add_to_cart 元数据不粘连 [英] WooCommerce add_to_cart metadata not sticking

查看:30
本文介绍了WooCommerce add_to_cart 元数据不粘连的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 WP 菜鸟,但对 PHP 非常熟悉.

I am a WP noob but very comfortable in PHP.

我正在与一位客户合作,我们已经构建了一个产品定制工具作为 Angular.js 单页应用程序.当产品完成定制后,我们试图将其注入 WooCommerce 购物车,以便客户可以结账.为此,我们将数据 $_POST 到 WP 安装根目录中的 PHP 文件.捕获它的代码如下所示:

I am working with a client and we have built a product customization tool as an Angular.js single page application. When the product is finished being customized we are seeking to inject it into a WooCommerce cart so the client can check out. To do this we are $_POSTing the data to a PHP file in the root directory of the WP install. The code to catch it looks like:

require_once('./wp-load.php' );

global $woocommerce;

$woocommerce->session->set_customer_session_cookie(true);
$woocommerce->cart->empty_cart();
$id_arr = $_GET['productID'];
$pdfName = $_GET['pdfName'];

for($i=0; $i<count($id_arr); $i++){
  $id = $id_arr[$i];
  if ($id==0) continue;
  if ($i==0){
    $ret = $woocommerce->cart->add_to_cart($id, 1, '', '', array('pdfName'=>$pdfName));
  }else{
    $ret = $woocommerce->cart->add_to_cart($id);
  }
}

wp_redirect(site_url().'/cart/');

产品都已正确添加到购物车,但结帐后没有元数据的迹象.经过广泛的研究,我在这里找到了一篇文章:https://wpml.org/forums/topic/woocommerce-add-to-cart-does-not-work-with-wpml-activated/ 告诉我插件会导致这种行为.所以我有两个具体问题?

The products are all correctly added to the cart but after checkout there is no sign of the metadata. After extensive research, I have found an article here: https://wpml.org/forums/topic/woocommerce-add-to-cart-does-not-work-with-wpml-activated/ that shows me that plugins can cause this behavior. So I have two specific questions?

  1. 我的代码是否有意义,我是否正确创建了元数据数组?
  2. 是否需要在 WooCommerce 中创建名为 pdfName 的内容才能执行此操作?
  3. 是否有另一种方法可以将元数据添加到订单中WooCommerce 可以解决这个问题吗?

推荐答案

您似乎正确添加了元数据.但是,一旦您刷新,WooCommerce 就会重新创建购物车数据.因此,当 WooCommerce 从存储的会话中拉出购物车时,您必须告诉 WooCommerce 维护元数据.好吧,至少这是我对它的理解.所以我认为你需要过滤你的 $cart_item 因为它是通过 woocommerce_get_cart_item_from_session 过滤器运行的:

It looks like you are adding the metadata correctly. However, as soon as you refresh, WooCommerce re-creates the cart data. Therefore you have to tell WooCommerce to maintain the metadata when it is pulling the cart from the stored session. Well, at least that is my understanding of it. So I think you need to filter thee $cart_item as it is run through the woocommerce_get_cart_item_from_session filter:

add_filter( 'woocommerce_get_cart_item_from_session', 'so_29660316_get_cart_item_from_session', 11, 2 );

function so_29660316_get_cart_item_from_session( $cart_item, $values ) {

    if ( isset( $values['pdfName'] ) ) {
            $cart_item['pdfName'] = $values['pdfName'];
    }
    return $cart_item;
}

这篇关于WooCommerce add_to_cart 元数据不粘连的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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