skip to Main Content

I have a standard form in WordPress and I am struggling with restricting access to the WordPress backend and properly working forms, because the forms are processed over wp-admin and if this is restricted, forms are not processed.

<form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
...
</form>

Restricting backend access:

// Restrict users to enter backend
add_action('init', 'restrict_backend_access');

function restrict_backend_access() {
    if (is_admin() && current_user_can('subscriber') && !(defined('DOING_AJAX') && DOING_AJAX)){
        wp_redirect( '/dashboard/' );
        exit;
    }
}

Am I missing something? I know that this is possible, because I build it many times, but this time something is different and I don’t know why.

Thank you!

2

Answers


  1. Please find correct code as below:

    add_action( 'init', 'restrict_backend_access' );
    
    function restrict_backend_access() {
        if( is_admin() && ! current_user_can( 'subscriber' ) && !( defined( ‘DOING_AJAX’ ) && DOING_AJAX ) ) {
            wp_redirect( home_url() );  
            exit;
        }
    }
    

    You can set redirect as per your requirement.
    As for example replace

    wp_redirect( home_url() ) 
    

    with

    wp_redirect( '/dashboard/' );
    
    Login or Signup to reply.
  2. You can add a hidden field to the form

    <form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
    ...
    <input type="hidden" name="admin_post_request" value="1" />
    </form>
    

    then use it to bypass the redirection

    add_action( 'init', 'restrict_backend_access' );
    function restrict_backend_access() {
        if( is_admin() && ! current_user_can( 'subscriber' ) && !( defined( ‘DOING_AJAX’ ) && DOING_AJAX && !isset( $_GET['admin_post_request'] ) ) ) {
            wp_redirect( home_url() );  
            exit;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search