gpt4 book ai didi

php - 如果状态更改为自定义状态,则向 WooCommerce 订单添加自定义元字段值

转载 作者:行者123 更新时间:2023-12-04 07:36:01 24 4
gpt4 key购买 nike

我已经在互联网上搜索了所有内容。我正在寻找的是创建一个自定义的 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' );
enter image description here
预先感谢您的帮助。

最佳答案

对于自定义订单状态,您可以使用 woocommerce_order_status_{$status_transition[to]}复合 Action Hook ,您将在此处替换 {$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 );

关于php - 如果状态更改为自定义状态,则向 WooCommerce 订单添加自定义元字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67737756/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com