Support

Account

Home Forums Front-end Issues Trigger Error on acf/save_post ?

Solved

Trigger Error on acf/save_post ?

  • I’m using the ACF Frontend Form to submit to an external API. Using the acf/save_post hook I’m posting to the API via wp_remote_post(). Is there a way at this point to trigger an error if the wp_remote_post() returns an error? Is there a better hook to do this kind of thing?

  • At that point there wouldn’t be a way to prevent the post from being submitted.

    Your only real option is to create an acf/validate_value https://www.advancedcustomfields.com/resources/acf-validate_value/ filters for the fields and do your own validation to make sure the values will be acceptable to where you are submitting them to.

    If there isn’t a way to know this ahead of time it would be extremely difficult.

  • You’re right that there wouldn’t be a way to prevent the post from being submitted but there is a way to prevent the post being saved which in my use-case works just as well.

    The acf/save_post hook with a priority less than 10 will fire before the post is saved. At this point I hit my API and if it fails I use the following code to redirect.

    global $wp;
    
    if( $apifailed ) {
    	
    	$_POST['acf'] = array();
    	$query_args = $_GET;
    	$query_args['updated'] = 'notupdated';
    	$query_args['errcode'] = 1;
    
    	wp_safe_redirect( add_query_arg( $query_args, home_url( $wp->request ) ) );
    	exit();
    	
    }

    ACF expected the updated query var parameter to not be empty ( it assumes 1 ) so to be clear that a post was not updated and that the updated parameter exists but is not empty I put a string message to indicate this.

    Finally, the ACF form runs validate right off the bat, always. At this point I can modify the args to handle the error code:

    /**
     * Modify the ACF Form args
     *
     * @param Array $args
     *
     * @return Array $args
     */
    function prefix_modify_form_args( $args ) {
    	
    	if( isset( $_GET['errcode'] ) ) {
    		
    		/**
    		 * Can switch the errcode but we'll go with something generic
    		 */
    		$args['updated_message'] = esc_html__( 'Something went wrong, XYZ not updated.' );
    		$args['html_updated_message'] = str_replace( 'class="updated"', 'class="error"', $args['html_updated_message'] );
    		
    	}
    	
    	return $args;
    	
    }
    add_filter( 'acf/validate_form', 'prefix_modify_form_args' );
Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Trigger Error on acf/save_post ?’ is closed to new replies.