I have searched all over the internet. What I’m looking for is to create a custom woocommerce order field which will be automatically added to the order when order status changes to wc-kurzuhradena
which the custom order status, with the value of current month and year. Example value: May 2021
So far I have this code which adds a custom field but I need to find a solution for a date when this status has been updated.
JavaScript
x
function add_date_field_shipped() {
global $woocommerce, $post;
$order = new WC_Order($post->ID);
if ( empty(get_post_meta( $post->ID, 'shipped', true)) && ('kurzuhrada' == $order->status)) {
update_post_meta( $post->ID, 'shipped', 'value here',true);
}
}
add_action( 'pre_get_posts', 'add_date_field_shipped' );
Thank you in advance for help.
Advertisement
Answer
For a custom order status you can use woocommerce_order_status_{$status_transition[to]}
composite action hook, where you will replace {$status_transition[to]}
by the custom status slug.
So you get:
JavaScript
function action_woocommerce_order_status_kurzuhradena( $order_id, $order ) {
// Set your default time zone (http://php.net/manual/en/timezones.php)
// Set your locale information (https://www.php.net/manual/en/function.setlocale.php)
date_default_timezone_set( 'Europe/Brussels' );
setlocale( LC_ALL, 'nl_BE' );
// Get current month & year
$month = strftime( '%B' );
$year = strftime( '%Y' );
// Update meta
$order->update_meta_data( 'shipped_date', $month . ' ' . $year );
$order->save();
}
add_action( 'woocommerce_order_status_kurzuhradena', 'action_woocommerce_order_status_kurzuhradena', 10, 2 );
To allow this only once, when changing to custom order status, use:
JavaScript
function action_woocommerce_order_status_kurzuhradena( $order_id, $order ) {
// Set your default time zone (http://php.net/manual/en/timezones.php)
// Set your locale information (https://www.php.net/manual/en/function.setlocale.php)
date_default_timezone_set( 'Europe/Brussels' );
setlocale( LC_ALL, 'nl_BE' );
// Get meta (flag)
$flag = $order->get_meta( 'shipped_date_flag' );
// NOT true
if ( ! $flag ) {
// Set flag
$flag = true;
// Update meta
$order->update_meta_data( 'shipped_date_flag', $flag );
// Get current month & year
$month = strftime( '%B' );
$year = strftime( '%Y' );
// Update meta
$order->update_meta_data( 'shipped_date', $month . ' ' . $year );
}
// Save
$order->save();
}
add_action( 'woocommerce_order_status_kurzuhradena', 'action_woocommerce_order_status_kurzuhradena', 10, 2 );