I am working on a WordPress website with multiple roles. My target is to redirect user with a specific role when they request pages like orders in the admin area to go to a filtered URL having their id.
example: User requests: www.site.com/wp-admin/edit.php?post_type=shop_order
User redirects to: www.site.com/wp-admin/edit.php?post_type=shop_order&wcb2bsa_sales_agent_search={current user id}
This Applies only to the role “tester”
My Approach was:
add_filter( 'user_has_cap', 'only_let_user_see', 10, 3 ); function only_let_user_see( $allcaps, $cap, $args ) { if($args[0] === 'edit_posts' && is_admin()) { $url = "https://"; $url.= $_SERVER['HTTP_HOST']; $url.= $_SERVER['REQUEST_URI']; $url.= 'wcb2bsa_sales_agent_search='; $url.= '100'; //fixed number for test purpose } if(current_user_can('tester')) { wp_redirect ($url); exit; }else { return $allcaps;}}
Rewriting the code now gave me error, Although when I was testing it it just worked but the problem was that user receives error: Too many redirects.
I really need help with this, So any suggestions would be appreciated. Thanks in advance.
Advertisement
Answer
The problem is with user_has_cap
filter in which user capabilities are required to return. In your code, you are redirecting the tester
user without passing capabilities so instead, you should use admin_init
action in order to redirect the user.
function redirect_users_by_role() { global $pagenow; if ($pagenow == 'edit.php' && $_REQUEST['post_type'] == 'shop_order' && current_user_can('shop_manager')) { $url = "https://"; $url.= $_SERVER['HTTP_HOST']; $url.= $_SERVER['REQUEST_URI']; $url.= '&wcb2bsa_sales_agent_search='; $url.= '100'; //fixed number for test purpose wp_redirect ($url); exit; } } add_action( 'admin_init', 'redirect_users_by_role' );
The above code is tested and working fine!