Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ErikBernskiold/c2687c38b3f478f2c117fe3d05fefeb8 to your computer and use it in GitHub Desktop.
Save ErikBernskiold/c2687c38b3f478f2c117fe3d05fefeb8 to your computer and use it in GitHub Desktop.
Simple code to prevent non-admins to access /wp-admin/, perfect for login-protected sites.
<?php
/**
* Class-based
**/
add_action( 'init', array( $this, 'prevent_non_admin_dashboard_access' ) );
public function prevent_non_admin_dashboard_access() {
if ( is_admin() && ! current_user_can( 'administrator' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}
/**
* Function-based
**/
add_action( 'init', 'bm_prevent_non_admin_dashboard_access' );
function bm_prevent_non_admin_dashboard_access() {
if ( is_admin() && ! current_user_can( 'administrator' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) {
wp_redirect( home_url() );
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment