我已经在互联网上搜索了所有内容。我正在寻找的是创建一个自定义 woocommerce 订单字段,当订单状态更改为自定义订单状态的 wc-kurzuhradena
时,该字段将自动添加到订单中,其值为当前月份和年份。示例值:May 2021
到目前为止,我有这段代码添加了一个自定义字段,但我需要为更新此状态的日期找到解决方案。
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' );
预先感谢您的帮助。
答案 0 :(得分:2)
对于自定义订单状态,您可以使用 woocommerce_order_status_{$status_transition[to]}
复合动作挂钩,您可以在其中将 {$status_transition[to]}
替换为自定义状态 slug。
所以你得到:
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 );
要只允许一次,当更改为自定义订单状态时,请使用:
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 );