Restrict woocommerce order status by role

余生颓废 提交于 2019-12-04 11:44:00

The conditional function current_user_can() is not recommended with user roles:

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

Instead you can get the current user and his roles (as a user can have many). Also the orders post status are very specific in woocommerce (they all begin by wc- and they should be in an array if many).

So the correct code should be:

<?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();
?>

Tested and works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!