Php 将索引数组转换为WooCommerce中可读的订单项元数据
添加自定义订单项元数据时遇到问题。我找到了一种方法,但看起来很糟糕。 守则:Php 将索引数组转换为WooCommerce中可读的订单项元数据,php,wordpress,woocommerce,metadata,hook-woocommerce,Php,Wordpress,Woocommerce,Metadata,Hook Woocommerce,添加自定义订单项元数据时遇到问题。我找到了一种方法,但看起来很糟糕。 守则: add_action('woocommerce_add_order_item_meta', 'func_add_custom_data_to_order_item_meta',1,2); function func_add_custom_data_to_order_item_meta( $item_id, $values ) { global $woocommerce,$wpdb; if(!emp
add_action('woocommerce_add_order_item_meta', 'func_add_custom_data_to_order_item_meta',1,2);
function func_add_custom_data_to_order_item_meta( $item_id, $values ) {
global $woocommerce,$wpdb;
if(!empty($values['custom'])){
$custom_order_meta = $values['custom'];
wc_add_order_item_meta($item_id, 'custom', serialize($custom_order_meta));
}
}
是否有任何方法可以遍历键值对,并每次在新行上获取它们的内容?已更新 自WooCommerce 3以来,钩子
WooCommerce\u add\u order\u item\u meta
已过时并被替换…请参阅
要获取独立可读的自定义订单项目数据(而不是序列化数组),请尝试以下操作:
add_action('woocommerce_checkout_create_order_line_item', 'add_custom_cart_item_data_as_order_item_meta', 10, 4 );
function add_custom_cart_item_data_as_order_item_meta( $item, $cart_item_key, $values, $order ) {
if( isset($values['custom']['length']) ){
$item->update_meta_data( 'Length', $values['custom']['length'] );
}
// elseif … ad so on
}
代码进入活动子主题(活动主题)的function.php文件 你答案中的代码没有给订单添加任何内容。仔细想想,我不想把项目元数据中的所有内容都添加到订单元数据中,只想添加某些条目,比如$values['custom']['length']。我尝试了一种不同的方法,使用action-woocmerce\u-add\u-order\u-item\u-meta,效果很好。请看我下面的评论。如果(!empty($values['custom']['length'])和&isset($values['custom']['length']){$custom_length=$values['custom']['length'];wc_add_order_item_meta($item_id,'Lengde i meter',$custom_length'));只需将我问题中的if语句替换为我评论中的if语句。我终于让它工作了。过了一段时间,我注意到您的代码中的函数名不匹配。我不应该如此依赖复制粘贴:p谢谢:)