php - 防止 WooCommerce 订单状态从/到特定状态更改
问题描述
您好我正在尝试在 mu-plugins 中创建一个功能,以防止某些用户将订单状态从特定订单状态更改为特定订单状态。
我一直在到处寻找,并且尝试了许多不同的方法,但似乎没有任何效果。
实际上该函数是使用woocommerce_order_status_changed
动作钩子运行的。问题是这个钩子在订单状态已经改变之后运行,是什么导致了无限循环。
我发现的最有用的钩子似乎是woocommerce_before_order_object_save
.
我在 WooCommerce Github 上找到了“添加附加参数以防止调用 'woocommerce_order_status_changed'”有用的相关线程。
我尝试使用@kloon代码片段解决方案:
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代码片段,我已经能够获得旧订单状态和新订单状态。然后我可以禁用从特定定义的订单状态到特定定义的订单状态的任何状态更改。
使用以下代码,特定定义的用户角色无法将订单状态从“处理中”更改为“暂停”:
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;
}
代码位于活动子主题(或活动主题)的 functions.php 文件中。测试和工作。
推荐阅读
- java - 如何在不使用 SwingUtilities 的情况下在 java 中创建两个完全独立的窗口?
- html5-audio - 将 URL 投射到 Chromecast 时,如何向它播放音频?
- python - 创建一个弹出窗口以确认退出 tkinter 应用程序
- javascript - 具有多个航点的路线规划器考虑使用谷歌地图的交通
- javascript - 使用nodejs测试js文件
- c# - C# 中的视觉小说决策结构
- tensorflow - libcublas.so.9.0:无法打开共享对象文件:Ubuntu 18.04 中没有这样的文件或目录
- sql - 如何执行用户定义的 Oracle 函数返回的 SQL 语句
- python - 使用布尔值选择 DataFrame 列
- node.js - nodejs数据库持续连接