在WooCommerce 3.0出现之前,我的代码就像一种魅力,可以将购物车中的自定义值保存到结帐时的订单中。但是自那时以来,我无法为订单创建自定义元。
环境: Wordpress 4.9.4和WooCommerce 3.3.3
add_action('woocommerce_checkout_update_order_meta', 'custom_meta_to_order', 20, 1);
add_action('woocommerce_checkout_create_order', 'custom_meta_to_order', 20, 1);
Hook数字1是我尝试最多的数字,2数字只是对该主题中提到的一些字面更改的实验。
以下功能代码与挂钩号1相关:
if (!function_exists('custom_meta_to_order')) {
function custom_meta_to_order($order_id, $values) {
$order = wc_get_order( $order_id );
$order->update_meta_data('_TESTKEYstart', 'Hello');
if (isset($values['myValue'])) {
$myValue = $values['myValue'];
if (!empty($myValue)) $order->update_meta_data('_myKey', $myValue);
}
$order->update_meta_data('_TESTKEYend', 'Bye');
$order->save();
}
}
我还在mySQL表中检查了table wp_woocommerce_order_itemmeta
是否至少会创建两个_TESTKEY * -meta - entrys(因为它们没有条件)。
更新:您的代码中有一些错误…
$values
不存在)$_POST['myValue']
改用。$order_id
对于 woocommerce_checkout_update_order_meta
$order
对于 woocommerce_checkout_create_order
在下面,我已替换为$_POST['myValue']
,$_POST['billing_country']
因为您没有提供此自定义结帐字段的代码…
所以这是两种方式:
1)对我来说,最好的办法,为解释在这里:
if ( ! function_exists('custom_meta_to_order') ) {
add_action( 'woocommerce_checkout_create_order', 'custom_meta_to_order', 20, 1 );
function custom_meta_to_order( $order ) {
$order->update_meta_data('_TESTKEYstart', 'Hello');
if (isset($_POST['billing_country'])) {
$myValue = $_POST['billing_country'];
if (!empty($myValue)) $order->update_meta_data('_my_key', $myValue);
}
$order->update_meta_data('_TESTKEYend', 'Bye');
}
}
代码进入您的活动子主题(或主题)的function.php文件中。经过测试和工作。
2)另一种方式:
if ( ! function_exists('custom_meta_to_order') ) {
add_action('woocommerce_checkout_update_order_meta', 'custom_meta_to_order', 20, 1);
function custom_meta_to_order( $order_id ) {
// get an instance of the WC_Order object
$order = wc_get_order( $order_id );
$order->update_meta_data('_TESTKEYstart', 'Hello');
if (isset($_POST['billing_country'])) {
$myValue = $_POST['billing_country'];
if (!empty($myValue)) $order->update_meta_data('_my_key', $myValue);
}
$order->update_meta_data('_TESTKEYend', 'Bye');
// Save the order data and meta data
$order->save();
}
}
代码进入您的活动子主题(或主题)的function.php文件中。经过测试和工作。
证据:
并且(在wp_postmeta
此订单ID的数据库表中):
在WooCommerce 3.3+版本中测试
您也可以使用旧方法(有效):
if ( ! function_exists('custom_meta_to_order') ) {
add_action('woocommerce_checkout_update_order_meta', 'custom_meta_to_order', 20, 1);
function custom_meta_to_order( $order_id ) {
update_post_meta( $order_id, '_TESTKEYstart', 'Hello' );
if ( isset( $_POST['billing_country'] ) ) {
$myValue = $_POST['billing_country'];
if (!empty($myValue))
update_post_meta( $order_id, '_my_key', $myValue);
}
update_post_meta( $order_id, '_TESTKEYend', 'Bye');
}
}
代码进入您的活动子主题(或主题)的function.php文件中。经过测试和工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句