Overview

The acf_form function allows you to easily create a front end form for data editing, however, this function can also be used not only to update existing data but to create new data entirely!

How

This is made possible by a filter run prior to saving any of the custom field data. The filter allows modification to the $post_id parameter and is called ‘acf/pre_save_post’.

By leveraging this filter, we can hook in and create a new post, then save the custom field data to this new post object!

Step 1: Create filter

The following code is to be placed within your functions.php file. The code hooks into a filter called ‘acf/pre_save_post’, creates a new post and returns the new post_id

<?php 
 
function my_pre_save_post( $post_id )
{
    // check if this is to be a new post
    if( $post_id != 'new' )
    {
        return $post_id;
    }
 
    // Create a new post
    $post = array(
        'post_status'  => 'draft' ,
        'post_title'  => 'A title, maybe a $_POST variable' ,
        'post_type'  => 'post' ,
    );  
 
    // insert the post
    $post_id = wp_insert_post( $post ); 
 
    // update $_POST['return']
    $_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );    
 
    // return the new ID
    return $post_id;
}
 
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
 
?>

Step 2: Create form

The following code is to be used on your page template which displays the form. Note that because of the custom post_id argument, the field groups that you wan tot display in the form need to be manually specified.

<?php 
 
/**
 * Template Name: Page with ACF form
 */
 
acf_form_head();
 
get_header(); 
 
the_post(); 
 
?>
 
	<div id="primary">
		<div id="content" role="main">
 
			<?php 
 
			$args = array(
				'post_id' => 'new',
				'field_groups' => array( 123 )
			);
 
			acf_form( $args ); 
 
			?>
 
		</div><!-- #content -->
	</div><!-- #primary -->
 
<?php get_sidebar(); ?>
<?php get_footer(); ?>