Prevent WooCommerce order status Change from / to specific statuses(防止WooCommerce订单状态从特定状态更改为特定状态)
问题描述
您好,我正在尝试在MU插件中创建一个函数,以防止某些用户将订单状态从特定订单状态更改为特定订单状态。
我到处找,试了很多不同的方法,但似乎都不管用。
实际上该函数正在使用woocommerce_order_status_changed
操作挂钩运行。问题是,此挂钩在订单状态更改后运行,这会导致无限循环。
我找到的最有用的钩子似乎是woocommerce_before_order_object_save
。
我在WooCommerce Github上找到了"Add an additional argument to prevent 'woocommerce_order_status_changed' from being called"有用的相关帖子。
我尝试使用@kloon code snippet solution:
add_filter( 'woocommerce_before_order_object_save', 'prevent_order_status_change', 10, 2 );
function prevent_order_status_change( $order, $data_store ) {
$changes = $order->get_changes();
if ( isset( $changes['status'] ) ) {
$data = $order->get_data();
$from_status = $data['status'];
$to_status = $changes['status'];
// Do your logic here and update statuses with CRUD eg $order->set_status( 'completed' );
// Be sure to return the order object
}
return $order;
}
但$changes
变量始终为空数组。
我尝试使用wp_insert_post_data
Wordpress hook,但当我设置时:
$data['post_status'] = "some status";
它只会阻止保存整个更新(整个新数据)。
这是我要运行的代码:
function($data){
if($data['order_status'] == 'comlpeted' && $data['new_order_status'] == 'proccessing'){
// prevent the order status from being changed
$data['new_order_status'] = $data['order_status'];
}
few more if conditions...
return $data;
}
感谢任何帮助或建议。
推荐答案
基于@kloon代码片段,我已经能够获得旧订单状态和新订单状态。然后我可以禁用从特定定义订单状态到特定定义订单状态的任何状态更改。
使用以下代码,特定定义的用户角色无法将订单状态从";处理更改为";on-保持:
add_filter( 'woocommerce_before_order_object_save', 'prevent_order_status_change', 10, 2 );
function prevent_order_status_change( $order, $data_store ) {
// Below define the disallowed user roles
$disallowed_user_roles = array( 'shop_manager');
$changes = $order->get_changes();
if( ! empty($changes) && isset($changes['status']) ) {
$old_status = str_replace( 'wc-', '', get_post_status($order->get_id()) );
$new_status = $changes['status'];
$user = wp_get_current_user();
$matched_roles = array_intersect($user->roles, $disallowed_user_roles);
// Avoid status change from "processing" to "on-hold"
if ( 'processing' === $old_status && 'on-hold' === $new_status && ! empty($matched_roles) ) {
throw new Exception( sprintf( __("You are not allowed to change order from %s to %s.", "woocommerce" ), $old_status, $new_status ) );
return false;
}
}
return $order;
}
代码放在活动子主题(或活动主题)的函数.php文件中。已测试并正常工作。
这篇关于防止WooCommerce订单状态从特定状态更改为特定状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:防止WooCommerce订单状态从特定状态更改为特定状态


基础教程推荐
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01