Search code examples
phpwordpresswoocommerceordersuser-roles

Show only current user's orders in WooCommerce admin orders list


I Already Created a custom role "Marron" who can access WordPress dashboard and see all WooCommerce orders.

But I want that "Marron" user role to be able to see only own orders in WP Admin Dashboard. (Just see without editing capabilities.)

I tried user role editor plugins, but none of them offers such functionality. Any suggestions?


Solution

  • You can use the following function code, that will display the current user orders in admin orders list, only for a defined user role (setting your user role SLUG in the code below):

    add_action( 'pre_get_posts', 'filter_admin_orders_list_user_orders' );
    function filter_admin_orders_list_user_orders( $query ) {
        global $pagenow, $typenow, $current_user;
    
        $user_role = 'marron'; // <== Here set the desire user role SLUG
    
        // Targeting WooCommerce admin orders list only
        if ( 'edit.php' === $pagenow && 'shop_order' === $typenow && in_array($user_role, $current_user->roles) ){
            $query->set('meta_query', array( array(
                'key' => '_customer_user',
                'value' => $current_user->ID,
            ) ) );
            
        }
        return $query;
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.