Security PHP Beginner

Keep Customers and Subscribers Out of wp-admin

Redirect users who can't edit content away from wp-admin to My Account or the homepage, without breaking AJAX.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 10 lines
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;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • WooCommerce already does something similar for customers. This snippet also covers subscribers and roles from membership plugins.
  • Users can no longer reach their profile in wp-admin. Make sure they can update their details somewhere else, such as WooCommerce’s Account details page.
  • Combine with “Remove the Admin Bar for Non-Admin Users” so the toolbar doesn’t link to wp-admin.

How to test it

Log in as a subscriber and visit /wp-admin/. You should land on My Account or the homepage.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only