Support

Account

Home Forums Front-end Issues Front-end acf_form() – Hooks Using Global $post

Solved

Front-end acf_form() – Hooks Using Global $post

  • I’m running into an issue with acf_form() where the hooks that are being passed $post_id are using the global $post. Is there a hook where I can modify this functionality?

    For example, I have an hook that given the name post_content will display the post content based on the passed ID.

    function themeprefix_acf_post_content( $value, $post_id ) {
    	
    	if( ! empty( $value ) ) {
    		return $value;
    	}
    	
    	return get_post_field( 'post_content', $post_id, 'edit' );
    	
    }
    add_filter( 'acf/load_value/name=post_content', 'themeprefix_acf_post_content', 10, 2 );

    The problem is on my front-end form if I have a field called post_content which I expect to be empty is instead filled with content from the actual page the form is on via global $post.

    The only solution to this I can think of is to overwrite the global $post object with an empty post object before calling acf_form() and then converting it back at the end of the call. I’m hoping there’s a hook or alternative to this so acf_form() field hooks aren’t using the global $post ID.

  • What I had was an ACF form on a frontend page where the user could create new posts. Something like this:

    acf_form( array(
    	'form'			=> true,
    	'id'			=> 'prefix-acf-form',
    	'post_id'		=> 'new_post',
    	'new_post'		=> array(
    		'post_type'		=> 'post_type_here',
    		'post_status'	=> 'publish',
    	),
    	'field_groups'	=> array( Class_Here::get_acf_key( 'edit' ) ),
    	'honeypot'		=> false,
    ) );

    The idea being that I would save post_content field as the actual post content for the post.

    The problem was that I was using global $post, so the pages content was being displayed instead of the expected nothing.

    The solution was to check if the passed $post_id is either empty or new_post and if it is, return the value early before attempting to get the post content.

    /**
     * Return post content if possible
     *
     * @param String $value - Field content
     * @param Mixed $post_id - Post ID, Empty, or 'new_post'
     *
     * @return String - Post content for given post ID
     */
    function themeprefix_acf_post_content( $value, $post_id ) {
    	
    	// We already have a value for some reason, return it.
    	if( ! empty( $value ) ) {
    		return $value;
    	}
    
    	// We do not have a $post_id to pull from, return early.
    	if( empty( $post_id ) || 'new_post' == $post_id ) {
    		return $value;
    	}
    	
    	return get_post_field( 'post_content', $post_id, 'edit' );
    	
    }
    add_filter( 'acf/load_value/name=post_content', 'themeprefix_acf_post_content', 10, 2 );
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Front-end acf_form() – Hooks Using Global $post’ is closed to new replies.