'Filter users and woocommerce orders by user meta for specific users

I have a WooCommerce store that utilizes the user switching plugin to allow sales reps to switch into customer accounts. Sales reps are only allowed to view/switch into their own customer accounts and cannot view other reps customers or admin accounts. I have done this by creating a custom user meta field and using the following code.

// kdickinson
add_action('pre_user_query','kdickinson_customers');
function kdickinson_customers( $u_query ) {
    $current_user = wp_get_current_user();
    if ($current_user->ID == '442') { 
        global $wpdb;
        $u_query->query_where = str_replace(
            'WHERE 1=1', 
            "WHERE 1=1 AND {$wpdb->users}.ID IN (
                SELECT {$wpdb->usermeta}.user_id FROM $wpdb->usermeta 
                    WHERE {$wpdb->usermeta}.meta_key = 'wpcf-sales-rep'
                    AND {$wpdb->usermeta}.meta_value LIKE '%kellie_dickinson%')", 
            $u_query->query_where
        );
    }
}

While this works, it is not very efficient, I have to rewrite the code for every single rep. Is there a way to make a single code work for everyone?

On a related note, I would like to add similar filtering to the woocommerce orders and only allow sales reps to see their customers orders. With my current code, sales reps can see all orders. I found a similar thread but I'm not too sure how to adapt it to my needs



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source