php - 按角色限制 woocommerce 订单状态

标签 php wordpress woocommerce status orders

我正在尝试建立一个工作流程,商店经理可以在其中创建订单并将其标记为“待付款”、“正在处理”,但只有管理员可以将订单标记为“完成”、“失败”等。

我找到的最接近的是 this post:

<?php 
if ( current_user_can(! 'administrator' ) ) {
$args = array( 'post_type' => 'post', 'post_status' => 'publish, pending, 
draft' );
} else {
$args = array( 'post_type' => 'post', 'post_status' => 'publish' );
}
$wp_query = new WP_Query($args); while ( have_posts() ) : the_post(); ?>
CONTENT
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>

这应该适用于常规的 WP 帖子(虽然我还没有测试过)但我不确定如何申请 Woocommerce。我最好的猜测是:

<?php 
if ( current_user_can(! 'administrator' ) ) {
$args = array( 'post_type' => 'shop_order', 'order_status' => 'complete,failed' );
} else {
$args = array( 'post_type' => 'shop_order', 'post_status' => 'pending-payment,processing' );
}
$wp_query = new WP_Query($args); while ( have_posts() ) : the_post(); ?>
CONTENT
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>

但是我遇到了各种各样的错误!我也不确定它是否只适用于编辑订单屏幕而不适用于管理商店订单表批量操作下拉列表。

非常感谢任何帮助!

最佳答案

条件函数current_user_can()不建议使用用户角色:

While checking against particular roles in place of a capability is supported in part, this practice is discouraged as it may produce unreliable results.

相反,您可以获得当前用户和他的角色(因为一个用户可以有很多)。 此外,订单发布状态在 woocommerce 中非常具体(它们都以 wc- 开头,如果有很多,它们应该在一个数组中)。

所以正确的代码应该是:

<?php 
    // get current user roles (if logged in)
    if( is_user_logged_in() ){
        $user = wp_get_current_user();
        $user_roles = $user->roles;
    } else $user_roles = array();

    // GET Orders statuses depending on user roles
    if ( in_array( 'shop_manager', $user_roles ) ) { // For "Shop Managers"
        $statuses = array( 'wc-pending','wc-processing' );
    } elseif ( in_array( 'administrator', $user_roles ) ) { // For admins (all statuses)
        $statuses = array_keys(wc_get_order_statuses());
    } else 
        $statuses = array();

    $loop = new WP_Query( array(
        'post_type'      => 'shop_order',
        'posts_per_page' => -1,
        'post_status'    => $statuses
    ) );

    if ( $loop->have_posts() ):
    while ( $loop->have_posts() ):
    $loop->the_post();
?>

<?php echo $loop->post->ID .', '; // Outputting Orders Ids (just for test) ?>

<?php
    endwhile;
    endif;
    wp_reset_postdata();
?>

已测试并有效

关于php - 按角色限制 woocommerce 订单状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46375749/

相关文章:

php - 部署 Symfony2 应用程序的首选方式是什么?

php - PHP 中的 Laravel header 和缓存

css - WOOCOMMERCE 单品布局定制

python - 如何使用 woocommerce api 更新 python 中的 stock_quantity

php - 将对象分配为值和引用在 PHP 中无法正常工作

php - 从数据库中选择并存储在数组中

facebook - 无法将我的域名添加到 Facebook 应用程序中的 'App Domains'

php - 如何在WordPress主题的不同页面上显示不同的 Logo ?

wordpress - 如何更改 WordPress 中的默认屏幕选项

wordpress - 是否可以在 WooCommerce API 订单端点中选择多个状态?