【发布时间】:2025-12-21 20:10:11
【问题描述】:
在 WooCommerce 中创建订单后,我尝试保存自定义元数据。我用woocommerce_new_order_item 钩子试了一下,总的来说它可以工作。但我需要存储订购产品的自定义属性..但我无法获取它。
我尝试了什么:
add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas
function add_basic_meta_for_new_quote($item_id, $values, $cart_item_key)
{
$angebotstext = get_post_meta($item_id, 'angebotstext', false);
wc_add_order_item_meta($item_id, 'angebotstext', $angebotstext);
}
或
add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas
function add_basic_meta_for_new_quote($item_id, $values, $cart_item_key)
{
global $product;
$angebotstext = $product->get_attribute( 'pa_angebotstext' );
wc_add_order_item_meta($item_id, 'angebotstext', $angebotstext);
}
属性保存在这里:
...meta_value 的结果始终为空、NULL 或 a:0:{}
你有什么想法吗?
-----编辑----
它以这种方式工作:
add_action('woocommerce_new_order_item','add_basic_meta_for_new_quote',10,3); // add extra order metas
function add_basic_meta_for_new_quote($item_id, $item, $order_id )
{
if ($order_id) {
$order = wc_get_order( $order_id );
}
# Iterating through each order items (WC_Order_Item_Product objects in WC 3+)
if ($order) {
foreach ( $order->get_items() as $item_id => $item_values ) {
// Product_id
$product_id = $item_values->get_product_id();
$product = wc_get_product($product_id);
$angebotstext = $product->get_attribute('Angebotstext');
if ( !empty($angebotstext) && $angebotstext != NULL ) {
wc_add_order_item_meta($item_id, 'Angebotstext' , $angebotstext);
}
}
}
}
但是:此代码将我的自定义属性两次添加为元......为什么? ????
【问题讨论】:
-
为什么不先尝试获取属性,然后使用“update_post_meta()”将订单更新为普通的 wp 帖子?因此该值将保存在订单页面内的自定义字段中,您可以随时轻松访问。
-
你有一个例子我怎么能做到这一点?
-
顺便说一句:我编辑了我的答案...还有另一个问题...:/
-
500(内部服务器错误)通常是由该 ajax 函数上的 PHP 代码 exaclty 的致命错误引起的(日志显示的 ywraq_submit_default_form 第 1 行)。在另一个世界中,这可能是您的代码无法完成整个任务的原因,因为它到达了函数 (ywraq_submit_default_form )。我可能需要更多日志来检查这一点,但我相信你需要检查这个函数“ywraq_submit_default_form”上的代码,因为它有错误。
-
感谢您的留言。请检查我编辑的代码。现在 500 不见了......但是:这段代码将我的自定义属性添加了两次作为元......为什么? ??????
标签: wordpress woocommerce hook-woocommerce