skip to Main Content

We are using User Role Editor Pro to manage user roles. We want to only display orders belonging to the respective "salesagent" (role).

I have been able to pull in the current user role and get access to the order columns on the correct page. I do not see any role information on the order: https://gist.github.com/leafdropco/2ae7281cc81864e74af28c507f3c2ad0

How can i only show orders to the correct agents?

// Hide products from agents that dont own them
add_action( 'manage_shop_order_posts_custom_column', 'display_sales_agent_orders_only' );
function display_sales_agent_orders_only( $columns ) {
    global $the_order, $post;
    
    if( is_user_logged_in() ) { // check if there is a logged in user 
        $user = wp_get_current_user(); // getting & setting the current user 
        $roles = ( array ) $user->roles; // obtaining the role
        if(in_array('sales_agent', $roles)) {
            $salesagentid = '60802fa984f32';
            if ( $salesagentid === $columns ) {
                print_r($columns);
            }
        }
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    Here is what worked for me:

    add_action( 'pre_get_posts', 'admin_pre_get_posts_orders_query', 9999 );
    function admin_pre_get_posts_orders_query( $query ) {
        global $pagenow;
        if (current_user_can('edit_others_shop_orders')) { return $query; }
        // Targeting admin orders list
        if( 'edit.php' == $pagenow &&
            $query->get( 'post_type' ) == 'shop_order'
          ) {
              $query->set( 'meta_query', array( array(
                    'key' => 'wcb2bsa_sales_agent', 
                    'value' => get_current_user_id() ) ) ); // Only displays the orders created by the current user
        }
    }
    

  2. To get the customer from an order, you can do:

    1. Woocommerce ways

    wc_get_orders and user_id parameter (see)

    $args = array(
        'customer_id' => $user_id
    );
    $orders = wc_get_orders($args);
    

    2. WordPress way

    With a custom wp_query on the Order post, and _customer_user post meta

    $customer = wp_get_current_user();
    // Get all customer orders
        $customer_orders = get_posts(array(
            'numberposts' => -1,
            'meta_key' => '_customer_user',
            'orderby' => 'date',
            'order' => 'DESC',
            'meta_value' => get_current_user_id(),
            'post_type' => wc_get_order_types(),
            'post_status' => array_keys(wc_get_order_statuses()),
        ));
    

    3 – get the user from an order Object

    If you want to retrieve the user_id of an order, see $order->get_user() or $order->get_user_id() (see)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search