Redirect users who can't edit content away from wp-admin to My Account or the homepage, without breaking AJAX.
add_action( 'admin_init', function (): void {
// Allow AJAX and admin-post.php form handlers, and anyone who can edit posts.
if ( wp_doing_ajax() || 'admin-post.php' === ( $GLOBALS['pagenow'] ?? '' ) || current_user_can( 'edit_posts' ) ) {
return;
}
$target = function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'myaccount' ) : home_url( '/' );
wp_safe_redirect( $target );
exit;
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Customers and subscribers have no reason to see wp-admin, and the dashboard confuses them. This snippet sends them to WooCommerce’s My Account page, or the homepage if you don’t use WooCommerce.
The check runs on admin_init, which fires on every wp-admin page. Anyone who can edit posts (contributors and above) is let through. Requests to admin-ajax.php and admin-post.php are also allowed, because front-end forms and plugins use them for logged-in visitors.
Log in as a subscriber and visit /wp-admin/. You should land on My Account or the homepage.