我知道问题的第一部分是可能的,但尚未找到如何向后端的所有订单添加自定义字段,然后使用默认值填充该字段。
我正在寻找创建一个名为“商家标识符”的自定义字段,然后使用默认名称(例如“ Company X”)填充该字段。
我看了一下这段代码,该代码在结帐时添加了一个输入值,然后在订单摘要中显示,但是我只需要将一个字段作为自定义字段添加到后端的每个订单中。
/**
* Process the checkout
*/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['billing_phone_new'] )
wc_add_notice( __( 'Phone 2 is compulsory. Please enter a value' ), 'error' );
}
/**
* Update the order meta with field value
*/
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['billing_phone_new'] ) ) {
update_post_meta( $order_id, 'billing_phone_new', sanitize_text_field( $_POST['billing_phone_new'] ) );
}
}
/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'my_custom_checkout_field_display_admin_order_meta', 10, 1 );
function my_custom_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('Phone 2').':</strong> <br/>' . get_post_meta( $order->get_id(), 'billing_phone_new', true ) . '</p>';
}
一旦该自定义字段出现在所有新旧订单上,我就可以添加此字段,并将其添加为计划的CSV导出中的一列(稍后再讲-我只需要实现第一部分)。
我不确定我是否需要先在结帐时使用默认值来隐藏字段,还是不确定是否可以使用不同的方法添加显示在后端所有订单上的自定义字段。
有人能帮忙吗?
谢谢
对于新订单,您可以使用以下命令
// Update the order meta with value
function action_woocommerce_checkout_update_order_meta( $order_id ) {
// Meta value
$meta_value = 'Company X';
update_post_meta( $order_id, 'merchant_identifier', $meta_value );
}
add_action( 'woocommerce_checkout_update_order_meta', 'action_woocommerce_checkout_update_order_meta', 10, 1 );
// OPTIONAL (will still work without this code, this is just to show it visually)
// Display field value on the order edit page
function action_woocommerce_admin_order_data_after_billing_address( $order ) {
echo '<p><strong>' . __( 'Merchant Identifier', 'woocommerce') . ':</strong> ' . $order->get_meta( 'merchant_identifier' ) . '</p>';
}
add_action( 'woocommerce_admin_order_data_after_billing_address', 'action_woocommerce_admin_order_data_after_billing_address', 10, 1 );
对于现有订单,您可以执行以下功能,该功能在执行(查看任何页面-前端)后可能会被删除。
// Run once, delete afterwards
function set_meta_for_old_orders () {
// Get ALL orders where meta key not exists
$orders = wc_get_orders( array(
'limit' => -1, // Query all orders
'meta_key' => 'merchant_identifier', // Post meta_key
'meta_compare' => 'NOT EXISTS', // Comparison argument
));
if ( ! empty ( $orders ) ) {
// Meta value
$meta_value = 'Company X';
foreach ( $orders as $order ) {
$order->update_meta_data( 'merchant_identifier', $meta_value );
$order->save();
}
echo 'Done!';
}
}
// Call function
add_action( 'wp_footer', 'set_meta_for_old_orders' );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句