Reputation: 2289
I have defined two custom fields for my Woocommerce orders. I used WooCommerce Admin Custom Order Fields extension to create these two fields.
When I manually create an order (/wp-admin/post-new.php?post_type=shop_order), I can see those fields and I can successfully add data and save the order.
I would, however, like to automatically populate one of those fields in the code. I'm trying to use the following code to do find out the meta key to that custom field so I can use update_post_meta()
to populate it, but this does not give me anything when I run it:
add_action('woocommerce_process_shop_order_meta', 'process_offline_order', 10, 2);
function process_offline_order ($post_id, $post) {
echo '<pre>';
print_r(get_post_meta($post_id));
die();
}
The documentation to that extension tells me that I can use something like get_post_meta($post_id, '_wc_acof_2')
with 2 being the ID of that custom field and I tried that too with no luck. It's not returning anything.
Below is an screen shot of my configuration screen:
Any idea how I can access/populate those fields and what hook to use if the one I'm using is not correct?
Upvotes: 1
Views: 1417
Reputation: 253849
You should try to use instead "save_post" action hook this way:
// Saving (Updating) or doing an action when submitting
add_action( 'save_post', 'update_order_custom_field_value' );
function update_order_custom_field_value( $post_id ){
// Only for shop order
if ( 'shop_order' != $_POST[ 'post_type' ] )
return $post_id;
// Checking that is not an autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user’s permissions (for 'shop_manager' and 'administrator' user roles)
if ( ! current_user_can( 'edit_shop_order', $post_id ) && ! current_user_can( 'edit_shop_orders', $post_id ) )
return $post_id;
// Updating custom field data
if( isset( $_POST['wc-admin-custom-order-fields'][2] ) ) {
// The new value
$value = 'Green';
// OR Get an Order meta data value ( HERE REPLACE "meta_key" by the correct metakey slug)
// $value = get_post_meta( $post_id, 'meta_key', true ); // (use "true" for a string or "false" for an array)
// Replacing and updating the value
update_post_meta( $post_id, '_wc_acof_2', $value );
}
}
// Testing output in order edit pages (below billing address):
add_action( 'woocommerce_admin_order_data_after_billing_address', 'display_order_custom_field_value' );
function display_order_custom_field_value( $order ){
foreach( get_option( 'wc_admin_custom_order_fields' ) as $id => $field ){
$value = get_post_meta( $order->get_id(), '_wc_acof_'.$id, true );
// Define Below the custom field ID to be displayed
if( $id == 2 && ! empty( $value ) ){
echo '<p><strong>' . $field['label'] . ':</strong> ' . $value . '</p>';
}
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Upvotes: 2