Support

Account

Home Forums ACF PRO acf_form front-end validation conflict using wp_redirect() to restrict back end

Solved

acf_form front-end validation conflict using wp_redirect() to restrict back end

  • Context:

    I’m using acf_form() to let some users with custom capabilities manage their own event via a front-end acf form I built.
    To check if the event’s date is allowed, I use acf/validate_save_post.

    The conflict:

    I also want to keep those users away from admin back-end, even if they’re logged in, so I used this simple function below:

    add_action( 'init', 'blockusers_init' ); 
     function blockusers_init() { 
     	if ( is_admin() && check_role('mycustomrole') ) { 
     		wp_redirect( home_url() ); 
     		exit; 
     		} 
    }

    this works well when the user tries to visit /wp-admin BUT, as long as he tries submitting my front-end acf form, validation fails and, instead of the red error tooltip, the page returns a default WordPress error and needs to be refreshed – see screenshots:

    The error tooltip I expect, with my custom validation message
    The error tooltip I expect, with my custom validation message

    The default WP error I get, showing all the fields with errors
    The default WP error I get, showing all the fields with errors

    Removing the blockusers_init() control solves the issue.
    It seems that wp_redirect() in init action is bad if acf/validate_save_post action is working at the same time.

    How can I get the two functions working togheter?
    Thanks in advance.

    Patrizio

  • acf/validate_save_post fires twice, the first is during an AJAX request to validate fields. During AJAX requests is_admin() is always true. You need to add a test for this

    
    add_action( 'init', 'blockusers_init' ); 
     function blockusers_init() { 
     	if ( is_admin() && check_role('mycustomrole') && 
                 (!defined(DOING_AJAX) || !DOING_AJAX)) { 
     		wp_redirect( home_url() ); 
     		exit; 
     		} 
    }
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.