Support

Account

Home Forums General Issues Frontend Form not populating right in backend

Solved

Frontend Form not populating right in backend

  • Hi there,
    I’m using a front-end form to add new posts to a custom post type. It’s kind of working, but I’m having a couple of issues:

    1. Since the first time I filled out the form and submitted it (as a test), it keeps pre-populating the fields the same way, and if I change them, they still save as the original way I’d entered. I’m assuming this is some sort of cache issue? or reset?

    2. I’m combining the results of 2 custom fields to create the custom post type title in admin. One of those custom fields is from the date picker. But I’m having trouble getting that to work properly.

    3. Client says she purchased the pro version of ACF, but what she installed is still the regular 4.4.7 – So I wonder if some of the code I’m using will only work when she installs the correct Pro files?

    4. How can I set the Submit button up such that once clicked the user gets a “Success” message, AND the fields they just entered display like a regular page? Like a confirmation page? Like, a final “yes, this is correct” or an “Edit these entries”?

    5. Finally, this code seems to dump the whole block of fields for the form all at once. Is there a way to enter them individually so I can lay things out in a more customized manner? Like, how I would use “echo $field” on a regular page?

    Here’s what I have in functions.php

    function cmin_pre_save_post( $post_id ) {
    	
    	$new_title_church_name = get_field('church_name', $post_id);
    	$new_title_date = get_field('start_date', $post_id);
    	
    	// make date object
    	$new_title_date = new DateTime($new_title_date);
    
        $new_title = "$new_title_church_name - $new_title_date->format('j M Y')" . '' . $value;
    	
    	//$new_title = get_field( 'church_name', $post_id) . ' ' . $value;
    	$new_slug = sanitize_title( $new_title );
    
        // check if this is to be a new post
        if( $post_id != 'new' )
        {
            return $post_id;
        }
    
        // Create a new post
        $post = array(
            'post_status'  => 'publish',
            'post_type'  => 'vbsform',
            'ID'          => $post_id,
    		'post_title'  => $new_title,
    		'post_name'   => $new_slug,
        );
    
        // 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' , 'cmin_pre_save_post' );

    And this is what is on the page itself:

    <?php
    add_action( 'get_header', 'cmin_do_acf_form_head', 1 );
    function cmin_do_acf_form_head() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        acf_form_head();
    }
     
    /**
     * Deregister the admin styles outputted when using acf_form
     */
    add_action( 'wp_print_styles', 'cmin_deregister_admin_styles', 999 );
    function cmin_deregister_admin_styles() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        wp_deregister_style( 'wp-admin' );
    }
    
    get_header(); ?>
    
    	<div id="primary" class="content-area">
    		
    		<div id="primary" class="content-area">
    		<div id="content" class="site-content" role="main">
    			
    			<?php /* The loop */
    				while ( have_posts() ) : the_post();
    				
    					// Retrieve a custom field value
    					$street = get_the_author_meta('street');
    					$church = get_field('church_name');
    					
    					if ( ! ( is_user_logged_in()|| current_user_can('publish_posts') ) ) {
    						echo '<p>You must be a registered author to post.</p>';
    						return;
        				}
    					
    					acf_form(array(
    						'post_id' => 'new',
    						'field_groups'	=> array( 2744 ),
    						'submit_value'	=> 'Submit this VBS event',
    						'updated_message'    => 'Saved!'
    					));
    					
    					acf_form( $new_post );
    					
    					echo $street;
    					
    				endwhile;
    				wp_reset_postdata(); ?>
    
    		</div><!-- #content -->
    	</div><!-- #primary -->
    
    <?php get_footer(); ?>

    I should add that I get the following error message at the bottom of the form:

    Warning: array_merge(): Argument #2 is not an array in /path/wp-content/plugins/advanced-custom-fields/core/api.php on line 1177 Warning: Invalid argument supplied for foreach() in /path/wp-content/plugins/advanced-custom-fields/core/api.php on line 1181

    Any ideas why it’s not saving the right way? I’ve copied and modified this code from various sources I’ve found on it, and I concede that my raw code-writing skills are not as high as I would like. But I’m usually pretty good at figuring out how to make a customization work if I have something to start with. This one’s throwing me a bit.

  • Hi @brotsky_pixie

    1. If you set acf_form() to save a new post, the form shouldn’t be prepopulated at all. Could you please share some screenshots of the issue?

    2. It seems that you wrapped the variables in quotes so it won’t show the right value. Also, I’m not sure what is $value variable. Could you please try the following code instead?

    $new_title = $new_title_church_name . '-' . $new_title_date->format('j M Y');

    3. The code you have should be working with ACF version 4. But I suggest you use ACF version 5 instead as it’s easier to use.

    4. The form should show the error messages if the values don’t pass the validation. You can also use the ‘return’ function to redirect it to a certain page if the post is successfully created. This page should give you more idea about it: https://www.advancedcustomfields.com/resources/acf_form/?version=4.

    5. There’s a ‘fields’ option to do it, but I’m afraid it will only work with the PRO version. This page should give you more idea about it: https://www.advancedcustomfields.com/resources/acf_form/.

    I hope this helps 🙂

  • Thank you so much for the reply. It’s about 1:30am for me right now so I only worked on Item 2 from your suggestion. It’s showing the *current* date now, but not the date selected in the date selector field. However, I wonder if Item #1 may be partially to blame.

    Better than a screenshot, here’s a link to the dev page. Maybe that’ll show you what’s going on. The first time you visit the page, you *should* have no fields pre-filled. And you *shouldn’t* have them pre-filled at *any* point you visit the page. But at least for me (I’m using FF), ever since the first time I filled out the form for testing purposes it remains filled out, and when I try to change a field (for instance, Church Name, which is part of the modified custom post type title), it saves in admin as the original entry I made, but when I click to edit/view, it shows the correct entry in the form itself – it’s just not saving it to the title properly.

    The other items I’ll look at when I’m up again. Thanks again.

  • Hi @brotsky_pixie

    The only one prepopulated is the “Adventist Church” field. I’m not so sure why, but maybe there’s a value saved in the database. If your client has the PRO version, I suggest you to use it instead. That’s because there are several new options that will make the process so much simpler.

    Thanks 🙂

  • Hi James,
    Thanks again for your help here. Client did upgrade to Pro (solving issue #3) and I believe I’ve gotten the appropriate codes modified now so I’m not having issues #1 anymore. YAY!

    I’m still having trouble with item #2 however. I get the first part of the title working properly, but the date it’s adding is today’s date, not the date entered in the start_date date picker field.

    Here’s what I have for that area. Perhaps you’ll see what I’m doing wrong:

    function vbsform_update_title( $value, $post_id, $field ) {
    	
    	$new_title_church_name = get_field( 'church_name', $post_id) . ' ' . $value;
    	
    	$new_title_date = get_field('start_date', $post_id);
    	
    	// make date object
    	$new_title_date = new DateTime($new_title_date);
    	
    	$new_title = $new_title_church_name . '-' . $new_title_date->format('M j, Y');
    	
    	$new_slug = sanitize_title( $new_title );
    	
    	// update post
    	$vbs_postdata = array(
    		'ID'          => $post_id,
    		'post_title'  => $new_title,
    		'post_name'   => $new_slug,
    	);	
    	
    	if ( ! wp_is_post_revision( $post_id ) ){
    	
    		// unhook this function so it doesn't loop infinitely
    		remove_action('save_post', 'vbs_update_title');
    	
    		// update the post, which calls save_post again
    		wp_update_post( $vbs_postdata );
    
    		// re-hook this function
    		add_action('save_post', 'vbs_update_title');
    	}	
    	
    	return $value;
    }

    Still working on items #4 & #5. Hopefully I’ll get those figured out in the meantime 🙂

  • I’m afraid the https://www.advancedcustomfields.com/resources/acf_form/ page really isn’t helping me much with my last issues.

    There are no examples of how to set up a custom layout with the ‘fields’ option (from what I can tell, it’s just a way to call certain fields from within the field group instead of all fields?), and, while I have my redirect page set up nicely, I’m not sure how to display what the user just submitted there. Should I be setting it up with some sort of custom loop? If so, I’m not sure how to grab the newly-created $post_id for the “single” template for that custom post type in my redirect.

    I suspect these things are obvious on the overview page to a guru such as yourself. I apologize in advance that the answers are not leaping out at me.

  • Hi @brotsky_pixie

    Could you please tell me which hook you used for the vbsform_update_title() function? I suggest you hook to “acf/save_post” with the priority of 20 instead. This page should give you more idea about it: https://www.advancedcustomfields.com/resources/acfsave_post/. That way you can get the field’s value by using the get_field() function.

    I think I have mistaken your question 🙁 Yes, the ‘fields’ option will only let you choose which fields you want to show. If you want to change the order, you need to do it from the backend (the field group editor page). You can also use the acf/render_field to add extra HTML before or after each field and the ‘html_before_fields’ and ‘html_after_fields’ options to add it before and after the fields.

    If you want to redirect the user to the newly created post, you can use this option instead:

    'return' => '%post_url%',

    If you need custom redirection, I think you can add wp_redirect() to the acf/save_post hook.

    I hope this helps 🙂

  • Hi there,
    I apologize for the delay. The long weekend got away from me.

    Ok, here’s where I’m at right now. I’m not sure what I had before our last go-around and what’s been since, so here’s all of it.

    functions.php

    add_filter('acf/pre_save_post' , 'cmin_do_pre_save_post' );
    function cmin_do_pre_save_post( $post_id ) {
     
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
     
        // check if this is to be a new post
        if( $post_id != 'new' ) {
            return $post_id;
        }
     
        // Create a new post
        $new_title_church_name = $_POST['acf']['field_577c12419eed1'];
    	
    	$new_title_date = get_field('start_date');
    	
    	// make date object
    	$new_title_date = new DateTime($new_title_date);
    	
    	$new_title = $new_title_church_name . ' - ' . $new_title_date->format('M j, Y');
    	
    	$new_slug = sanitize_title( $new_title );
        
        $post = array(
            'post_type'     => 'vbsform', // Your post type ( post, page, custom post type )
            'post_status'   => 'publish', // (publish, draft, private, etc.)
            'post_title'    => wp_strip_all_tags($new_slug), // Post Title ACF field key
            //'post_content'  => $_POST['acf']['field_54dfc94e35ec5'], // Post Content ACF field key
        );
     
        // insert the post
        $post_id = wp_insert_post( $post );
     
        // Save the fields to the post
        do_action( 'acf/save_post' , $post_id );
     
        return $post_id;
     
    }

    Form Page

    <?php
    
    function my_kses_post( $value ) {
    	// is array
    	if( is_array($value) ) {
    		return array_map('my_kses_post', $value);
    	}
    	// return
    	return wp_kses_post( $value );
    }
    
    add_filter('acf/update_value', 'my_kses_post', 10, 1);
    	
    add_action( 'get_header', 'cmin_do_acf_form_head', 1 );
    function cmin_do_acf_form_head() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        acf_form_head();
    }
    
    add_action( 'wp_print_styles', 'cmin_deregister_admin_styles', 999 );
    function cmin_deregister_admin_styles() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        wp_deregister_style( 'wp-admin' );
    }
     
    get_header(); ?>
    
    <div  class="page-wrapper">
    	<div class="row">
    		<div id="content" class="large-12 columns" role="main">
    			
    			<?php /* The loop */
    				if ( ! ( is_user_logged_in()|| current_user_can('publish_posts') ) ) {
            echo '<p>You must be a registered author to post.</p>';
            return;
        }
        
        while ( have_posts() ) : the_post();
     
        $new_post = array(
            'post_id'            => 'new', // Create a new post
            // PUT IN YOUR OWN FIELD GROUP ID(s)
            'field_groups'       => array(2793), // Create post field group ID(s)
            'form'               => true,
            'return'             => '%post_url%', // Redirect to new post url
            'html_before_fields' => '',
            'html_after_fields'  => '',
            'submit_value'       => 'Submit VBS Event',
            'updated_message'    => 'Saved!'
        );
        acf_form( $new_post );
        
        endwhile; ?>
    
    		</div><!-- #content -->
    	</div><!-- #row -->
    </div><!-- #page-wrapper -->
    
    <?php acf_enqueue_uploader(); ?>
    
    <script type="text/javascript">
    (function($) {
    	
    	// setup fields
    	acf.do_action('append', $('#popup-id'));
    	
    })(jQuery);	
    </script>
    
    <?php get_footer(); ?>

    Most everything is working swimmingly, except I still cannot seem to get the start_date field to display in the title. It only displays the CURRENT date. Not sure why. I have the field date called. AND I once more have a pre-populated field, and I’m not sure why. I thought that had been solved previously, but it’s back. Grrrrrr

  • Hi @brotsky_pixie

    With ACF PRO, you don’t need to use the acf/pre_save_post hook and wp_insert_post() function anymore. You can use the ‘new_post’ option and provide it with the wp_insert_post()‘s parameters instead. This page should give you more idea about it: https://www.advancedcustomfields.com/resources/using-acf_form-to-create-a-new-post/.

    After that, you can change the title like this:

    //Auto add and update Title field:
    function my_post_title_updater( $post_id ) {
        
        // get the church name
        $new_title_church_name = get_field('curch_name_field', $post_id);
    
        // get the selected date and the current date
        $new_title_date = get_field('start_date', $post_id);
        $new_title_current_date = new DateTime($new_title_date);
        
        // set the title
        $new_title = $new_title_church_name . ' - ' . $new_title_date . ' - ' . $new_title_date->format('M j, Y');
    
        // create the update data holder
        $my_post = array();
        $my_post['ID'] = $post_id;
        $my_post['title'] = $new_title;
    
        //Unhook function to prevent infitnite looping
        remove_action('acf/save_post', 'my_post_title_updater', 20);
    
        // Update the post into the database
        wp_update_post( $my_post );
    
        //Rehook function to prevent infitnite looping
        add_filter('acf/save_post', 'my_post_title_updater', 20);
    
    }
    // run after ACF saves the $_POST['fields'] data
    add_action('acf/save_post', 'my_post_title_updater', 20);

    I hope this helps 🙂

  • I’m feeling pretty dense right about now. Honestly, I’m trying to get this figured out, and have looked at the links you’ve sent and tried a ridiculous number of combinations of things. But now the title isn’t working at all.

    I removed the section from functions that you said was no longer necessary. Replaced it with what’s below.

    The new title shows properly in the body of the resulting post page, but it isn’t reflected as either the title or the slug. So, for instance, the latest new post from this form resulted in a slug of “vbsform/3024-2/”, instead of “vbsform/title-start_date/”

    Functions.php

    //Auto add and update Title field:
    function vbs_post_title_updater( $post_id ) {
        
        // get the church name
        $new_title_church_name = get_field('church_name', $post_id);
    
        // get the selected date and the current date
        $new_title_date = get_field('start_date', $post_id);
        $new_title_date = new DateTime($new_title_date);
        
        // set the title
        $new_title = $new_title_church_name . ' - ' . $new_title_date->format('M j, Y');
    
        // create the update data holder
        $vbs_post = array();
        $vbs_post['ID'] = $post_id;
        $vbs_post['title'] = $new_title;
    
        //Unhook function to prevent infitnite looping
        remove_action('acf/save_post', 'vbs_post_title_updater', 20);
    
        //Rehook function to prevent infitnite looping
        add_filter('acf/save_post', 'vbs_post_title_updater', 20);
    
    }
    // run after ACF saves the $_POST['fields'] data
    add_action('acf/save_post', 'vbs_post_title_updater', 20);

    Form Page

    <?php
    
    function my_kses_post( $value ) {
    	// is array
    	if( is_array($value) ) {
    		return array_map('my_kses_post', $value);
    	}
    	// return
    	return wp_kses_post( $value );
    }
    
    add_filter('acf/update_value', 'my_kses_post', 10, 1);
    	
    add_action( 'get_header', 'cmin_do_acf_form_head', 1 );
    function cmin_do_acf_form_head() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        acf_form_head();
    }
    
    add_action( 'wp_print_styles', 'cmin_deregister_admin_styles', 999 );
    function cmin_deregister_admin_styles() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        wp_deregister_style( 'wp-admin' );
    }
     
    get_header(); ?>
    
    <div  class="page-wrapper">
    	<div class="row">
    		<div id="content" class="large-12 columns" role="main">
    			
    			<?php /* The loop */
    				if ( ! ( is_user_logged_in()|| current_user_can('publish_posts') ) ) {
            echo '<p>You must be a registered author to post.</p>';
            return;
        }
        
        $vbs_post = array(
    		'post_id'		=> 'new_post',
    		'post_title'	=> wp_strip_all_tags($new_title),
    		'post_content'	=> false,
    		'form' => true,
    		'new_post'		=> array(
    			'post_type'		=> 'vbsform',
    			'post_status'	=> 'publish'
    		),
    		'field_groups'       => array(2793),
    		'return'             => '%post_url%',
    		'submit_value'       => 'Submit VBS Event',
    		'updated_message'    => 'Saved!',
    		'post_title'    => wp_strip_all_tags($new_slug),
    	);
    	
    	acf_form( $vbs_post );
        
        </div><!-- #content -->
    	</div><!-- #row -->
    </div><!-- #page-wrapper -->
    
    <?php acf_enqueue_uploader(); ?>
    
    <script type="text/javascript">
    (function($) {
    	
    	// setup fields
    	acf.do_action('append', $('#popup-id'));
    	
    })(jQuery);	
    </script>
    
    <?php get_footer(); ?>

    Results Page

    <?php
    function my_kses_post( $value ) {
    	// is array
    	if( is_array($value) ) {
    		return array_map('my_kses_post', $value);
    	}
    	// return
    	return wp_kses_post( $value );
    }
    
    add_filter('acf/update_value', 'my_kses_post', 10, 1);
    	
    add_action( 'get_header', 'cmin_do_acf_form_head', 1 );
    function cmin_do_acf_form_head() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        acf_form_head();
    }
    
    get_header(); 
    ?>
    
    <?php 
    // Create big featured image if set
    if($flatsome_opt['blog_post_style'] == 'big-featured-image') { ?>
    <div class="parallax-title">
    <?php while ( have_posts() ) : the_post(); ?>
    	<?php ob_start(); ?>
    	<header class="entry-header text-center">
    		<div class="tx-div small"></div>
    		<?php if ( 'post' == get_post_type() ) : ?>
    		<div class="entry-meta">
    			<?php the_date('F j, Y', 'Submitted on ', ''); ?>
    		</div>
    	</header>
    <?php endwhile; // end of the loop. ?>
    </div>
    <?php } ?>
    
    <div class="page-wrapper page-<?php echo $flatsome_opt['blog_post_layout']; ?>">
    	<div class="row">
    		
    		<div class="page-inner">
    			
    			<?php /* The loop */
    				if ( ! ( is_user_logged_in()|| current_user_can('publish_posts') ) ) {
            echo '<p>You must be a registered author to post.</p>';
            return;
        } ?>
    		<?php while ( have_posts() ) : the_post(); ?>
    
    			<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    	<?php if($flatsome_opt['blog_post_style'] == 'default' || !isset($flatsome_opt['blog_post_style'])) { ?> 
    	<header class="entry-header text-center">
    		<h1 class="entry-title"><?php the_title(); ?></h1>
    		<div class="tx-div small"></div>
    		<div class="entry-meta">
    			<?php the_date('F j, Y', 'Submitted on ', ''); ?> by <?php the_author(); ?><br>
    			This post was last modified by <?php the_modified_author(); ?> on <?php the_modified_date('F j, Y'); ?> at <?php the_modified_date('g:i a'); ?>
    		</div><!-- .entry-meta -->
    	</header><!-- .entry-header -->
    
    	<div class="entry-content">
    		
    		<?php $author_id = get_the_author_meta('ID');
    		$author_phone = get_field('phone_number', 'user_'. $author_id );
    		$term = get_field('conference');
    		$start_date = get_field('start_date', false, false);
    			$start_date = new DateTime($start_date);
    		$end_date = get_field('end_date', false, false);
    			$end_date = new DateTime($end_date);
    		$images = get_field('images');
    		 ?>
    		
    		<table class="table table-striped">
    			<tr>
    				<td>Church Name</td>
    				<td><?php the_field('church_name'); ?> Adventist Church</td>
    			</tr>
    			
    			<?php if( $term ): ?>
    			<tr>
    				<td>Conference</td>
    				<td><?php echo $term->name; ?></td>
    			</tr>
    			<?php endif; ?>
    			
    			<tr>
    				<td>Contact Person</td>
    				<td><?php the_author(); ?></td>
    			</tr>
    			
    			<tr>
    				<td>E-mail address</td>
    				<td><?php the_author_meta('user_email'); ?></td>
    			</tr>
    			
    			<tr>
    				<td>Phone Number</td>
    				<td><?php echo $author_phone; ?></td>
    			</tr>
    			
    			<tr>
    				<td>I am the...</td>
    				<td><?php the_field('i_am'); ?></td>
    			</tr>
    			
    			<tr>
    				<td>Start Date</td>
    				<td><?php echo $start_date->format('F j, Y'); ?></td>
    			</tr>
    			
    			<tr>
    				<td>End Date</td>
    				<td><?php echo $end_date->format('F j, Y'); ?></td>
    			</tr>
    			
    			<?php if( $images ) { ?>
    			<tr>
    				<td>Images</td>
    				<td>
    					<ul>
    					<?php foreach( $images as $image ): ?>
    						<li>
    							<a href="<?php echo $image['url']; ?>">
    								<img src="<?php echo $image['sizes']['admin-thumb']; ?>" alt="<?php echo $image['alt']; ?>" />
    							</a>
    						</li>
    					<?php endforeach; ?>
        				</ul>
        			</td>
    			</tr>
    			<?php } ?>
    			
    		</table>
    		
    		<div class="edit-form">Edit this VBS submission</div>
    			
    		<div class="vbs-off"><?php acf_form(); ?></div>
    		
    	</div><!-- .entry-content -->
    	
    	<script>
    		$ = jQuery;
    			$(".edit-form").click(function(){
    				$(".vbs-off").toggleClass("vbs-on");
    				$(this).toggleClass("vbs-on");
    			}, function() {
    				$(".vbs-off").toggleClass("vbs-on");
    			});
    	</script>
    	
    </article>
    
    		<?php endwhile; // end of the loop. ?>
    
    		
    	
    		</div><!-- .page-inner -->
    	</div><!-- #content -->
    
    	<div class="large-3 columns left">
    		<?php get_sidebar(); }?>
    	</div><!-- end sidebar -->
    
    </div><!-- end row -->	
    </div><!-- end page-wrapper -->
    
    <?php acf_enqueue_uploader(); ?>
    
    <script type="text/javascript">
    (function($) {
    	
    	// setup fields
    	acf.do_action('append', $('#popup-id'));
    	
    })(jQuery);	
    </script>
    
    <?php get_footer(); ?>
  • Hi @brotsky_pixie

    I think I gave you the wrong code. I’m sorry about that. Please try this one instead:

    // create the update data holder
    $vbs_post = array();
    $vbs_post['ID'] = $post_id;
    $vbs_post['post_title'] = $new_title;

    If you want to change the post slug, please try this code:

    $vbs_post['post_name'] = 'this-is-the-new-slug';

    Please check this page for more parameters: https://developer.wordpress.org/reference/functions/wp_insert_post/.

    Also, please don’t forget to save the changes like this:

    //Unhook function to prevent infitnite looping
    remove_action('acf/save_post', 'vbs_post_title_updater', 20);
    
    // Update the post into the database
    wp_update_post( $vbs_post );
    
    //Rehook function to prevent infitnite looping
    add_filter('acf/save_post', 'vbs_post_title_updater', 20);

    Hope this helps 🙂

  • AHHHHH!!!!! You rock! Thank you SO much! It’s now fixed!

    For anyone else who needs the complete code, here you go:

    Functions.php

    //Auto add and update Title field:
    function your_post_title_updater( $post_id ) {
        
        // get the field name
        $new_title_field_name = get_field('your_field_name', $post_id);
    
        // get the selected date and the current date
        $new_title_date = get_field('start_date', $post_id);
        $new_title_date = new DateTime($new_title_date);
        
        // set the title
        $new_title = $new_title_field_name . ' - ' . $new_title_date->format('M j, Y');
        
        $new_slug = sanitize_title( $new_title );
    
        // create the update data holder
    	$your_post = array();
    	$your_post['ID'] = $post_id;
    	$your_post['post_title'] = $new_title;
    	$your_post['post_name'] = wp_strip_all_tags($new_slug);
    
        //Unhook function to prevent infitnite looping
    	remove_action('acf/save_post', 'your_post_title_updater', 20);
    
    	// Update the post into the database
    	wp_update_post( $your_post );
    
    	//Rehook function to prevent infitnite looping
    	add_filter('acf/save_post', 'your_post_title_updater', 20);
    
    }
    // run after ACF saves the $_POST['fields'] data
    add_action('acf/save_post', 'your_post_title_updater', 20);

    Your form display page

    <?php
    
    function my_kses_post( $value ) {
    	// is array
    	if( is_array($value) ) {
    		return array_map('my_kses_post', $value);
    	}
    	// return
    	return wp_kses_post( $value );
    }
    
    add_filter('acf/update_value', 'my_kses_post', 10, 1);
    	
    add_action( 'get_header', 'your_do_acf_form_head', 1 );
    function your_do_acf_form_head() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        acf_form_head();
    }
    
    add_action( 'wp_print_styles', 'your_deregister_admin_styles', 999 );
    function your_deregister_admin_styles() {
        // Bail if not logged in or not able to post
        if ( ! ( is_user_logged_in() || current_user_can('publish_posts') ) ) {
            return;
        }
        wp_deregister_style( 'wp-admin' );
    }
     
    get_header(); ?>
    
    <div  class="page-wrapper">
    	<div class="row">
    		<div id="content">
    			
    			<?php /* The loop */
    				if ( ! ( is_user_logged_in()|| current_user_can('publish_posts') ) ) {
            echo '<p>You must be a registered author to post.</p>';
            return;
        }
        
        $your_post = array(
    		'post_id'		=> 'new_post',
    		'post_title'	=> wp_strip_all_tags($new_title),
    		'post_content'	=> false,
    		'form' => true,
    		'new_post'		=> array(
    			'post_type'		=> 'your_post_type',
    			'post_status'	=> 'publish'
    		),
    		'field_groups'       => array(2793),
    		'return'             => '%post_url%',
    		'submit_value'       => 'Submit',
    		'updated_message'    => 'Saved!',
    		'post_title'    => wp_strip_all_tags($new_slug),
    	);
    	
    	acf_form( $your_post );
    
    		</div><!-- #content -->
    	</div><!-- #row -->
    </div><!-- #page-wrapper -->
    
    <?php acf_enqueue_uploader(); ?>
    
    <script type="text/javascript">
    (function($) {
    	
    	// setup fields
    	acf.do_action('append', $('#popup-id'));
    	
    })(jQuery);	
    </script>
    
    <?php get_footer(); ?>
  • All was working sooooo swimmingly! I was thrilled! Until…

    The client has asked for several related custom post types. They require different types of titles. I thought I could just duplicate the functions used above making minor modifications so they were unique, but it breaks the whole thing. There’s gotta be some sort of syntax I’m missing here to make it happen.

    Here’s what I’ve got:

    Functions.php

    //Auto add and update Title field for English/Yes form:
    function vbs_post_title_updater( $post_id ) {
        
        // get the church name
        $new_title_church_name = get_field('church_name', $post_id);
    
        // get the selected date and the current date
        $new_title_date = get_field('start_date', $post_id);
        $new_title_date = new DateTime($new_title_date);
        
        // set the title
        $new_title = $new_title_church_name . ' - ' . $new_title_date->format('M j, Y');
        
        $new_slug = sanitize_title( $new_title );
    
        // create the update data holder
    	$vbs_ey_post = array();
    	$vbs_ey_post['ID'] = $post_id;
    	$vbs_ey_post['post_title'] = $new_title;
    	$vbs_ey_post['post_name'] = wp_strip_all_tags($new_slug);
    
        //Unhook function to prevent infitnite looping
    	remove_action('acf/save_post', 'vbs_post_title_updater', 20);
    
    	// Update the post into the database
    	wp_update_post( $vbs_ey_post );
    
    	//Rehook function to prevent infitnite looping
    	add_filter('acf/save_post', 'vbs_post_title_updater', 20);
    
    }
    // run after ACF saves the $_POST['fields'] data
    add_action('acf/save_post', 'vbs_post_title_updater', 20);
    
    //Auto add and update Title field for English/No form:
    function vbs_post_title_updater2( $post_id2 ) {
        
        // get the church name
        $new_title_church_name2 = get_field('church_name2', $post_id2);
    
        // set the title
        $new_title2 = $new_title_church_name2;
        
        $new_slug2 = sanitize_title( $new_title2 );
    
        // create the update data holder
    	$vbs_en_post = array();
    	$vbs_en_post['ID'] = $post_id2;
    	$vbs_en_post['post_title'] = $new_title2;
    	$vbs_en_post['post_name'] = wp_strip_all_tags($new_slug2);
    
        //Unhook function to prevent infinite looping
    	remove_action('acf/save_post', 'vbs_post_title_updater2', 20);
    
    	// Update the post into the database
    	wp_update_post( $vbs_ey_post );
    
    	//Rehook function to prevent infitnite looping
    	add_filter('acf/save_post', 'vbs_post_title_updater2', 20);
    
    }
    // run after ACF saves the $_POST['fields'] data
    add_action('acf/save_post', 'vbs_post_title_updater2', 20);

    Page – English/Yes

    $vbs_ey_post = array(
    		'post_id'		=> 'new_post',
    		'post_title'	=> wp_strip_all_tags($new_title),
    		'post_content'	=> false,
    		'form' => true,
    		'new_post'		=> array(
    			'post_type'		=> 'ey',
    			'post_status'	=> 'publish'
    		),
    		'field_groups'       => array(2793),
    		'return'             => '%post_url%',
    		'submit_value'       => 'Submit VBS Event',
    		'updated_message'    => 'Saved!'
    	);
    	
    	acf_form( $vbs_ey_post ); ?>

    Page – English/No

    $vbs_en_post = array(
    		'post_id'		=> 'new_post',
    		'post_title'	=> wp_strip_all_tags($new_title2),
    		'post_content'	=> false,
    		'form' => true,
    		'new_post'		=> array(
    			'post_type'		=> 'en',
    			'post_status'	=> 'publish'
    		),
    		'field_groups'       => array(3052),
    		'return'             => '%post_url%',
    		'submit_value'       => 'Submit',
    		'updated_message'    => 'Saved!',
    		'post_title'    => wp_strip_all_tags($new_slug2),
    	);
    	
    	acf_form( $vbs_en_post ); ?>

    As long as I only have the first function running, the one form works great. It saves the title, redirects, all of it. If I add the one for English/No, Neither one of them redirect or save titles properly.

    Note: I have reflushed permalinks several times through this process.

    It just occurred to me that it might be helpful to see the custom post type functions as well, since *maybe* something about them is part of the issue?

    Custom Post Types

    add_action('init', 'ey');
    function ey()
    {
    	$labels = array(
    		'name_admin_bar' => 'VBS Submissions',
    		'all_items' => 'All English/Yes Submissions',
    		'name' => 'English/Yes Submission',
    		'singular_name' => 'English/Yes Submission',
    		'menu_name' => 'VBS Submissions',
    		'add_new' => false,
    		'add_new_item' => 'Add New English/Yes Submission',
    		'edit' => 'Edit',
    		'edit_item' => 'Edit English/Yes Submission',
    		'new_item' => 'New English/Yes Submission',
    		'view' => 'View English/Yes Submission',
    		'view_item' => 'View English/Yes Submission',
    		'search_items' => 'Search English/Yes Submissions',
    		'not_found' => 'No English/Yes Submission Found',
    		'not_found_in_trash' => 'No English/Yes Submission Found in Trash',
    		'parent' => 'Parent English/Yes Submission',
    	);
    		
    	$args = array(
    		'label' => 'VBS Submissions',
    		'labels' => $labels,
    		'description' => '',
    		'public' => true,
    		'show_ui' => true,
    		'show_in_menu' => true,
    		'capability_type' => 'post',
    		'hierarchical' => true,
    		'rewrite' => array(
    			'slug' => ''
    		),
    		'menu_icon' => 'dashicons-smiley',
    		'query_var' => true,
    		'exclude_from_search' => false,
    		'supports' => array( 'author', 'title' ),
    		'menu_position' => 5,
    		'add_new' => false,
    	);
    		
    register_post_type( 'ey' , $args );
    }
    
    add_action('init', 'en');
    function en()
    {
    	$labels = array(
    		'all_items' => 'All English/No Submissions',
    		'name' => 'English/No Submission',
    		'singular_name' => 'English/No Submission',
    		'menu_name' => 'English/No Submission',
    		'add_new' => 'VBS English/No Submission',
    		'add_new_item' => 'Add New English/No Submission',
    		'edit' => 'Edit',
    		'edit_item' => 'Edit English/No Submission',
    		'new_item' => 'New English/No Submission',
    		'view' => 'View English/No Submission',
    		'view_item' => 'View English/No Submission',
    		'search_items' => 'Search English/No Submissions',
    		'not_found' => 'No English/No Submission Found',
    		'not_found_in_trash' => 'No English/No Submission Found in Trash',
    		'parent' => 'Parent English/No Submission',
    	);
    		
    	$args = array(
    		'label' => 'English/No Submissions',
    		'labels' => $labels,
    		'description' => '',
    		'public' => true,
    		'show_ui' => true,
    		'show_in_menu' => true,
    		'capability_type' => 'post',
    		'hierarchical' => true,
    		'rewrite' => array(
    			'slug' => ''
    		),
    		'query_var' => true,
    		'exclude_from_search' => false,
    		'supports' => array( 'author', 'title' ),
    		'show_in_menu'  =>	'edit.php?post_type=ey',
    		'menu_position' => 2
    	);
    		
    register_post_type( 'en' , $args );
    }
    
    add_action('init', 'sy');
    function sy()
    {
    	$labels = array(
    		'all_items' => 'All Spanish/Yes Submissions',
    		'name' => 'Spanish/Yes Submission',
    		'singular_name' => 'Spanish/Yes Submission',
    		'menu_name' => 'Spanish/Yes Submission',
    		'add_new' => 'Spanish/Yes Submission',
    		'add_new_item' => 'Add New Spanish/Yes Submission',
    		'edit' => 'Edit',
    		'edit_item' => 'Edit Spanish/Yes Submission',
    		'new_item' => 'New Spanish/Yes Submission',
    		'view' => 'View Spanish/Yes Submission',
    		'view_item' => 'View Spanish/Yes Submission',
    		'search_items' => 'Search Spanish/Yes Submissions',
    		'not_found' => 'No Spanish/Yes Submission Found',
    		'not_found_in_trash' => 'No Spanish/Yes Submission Found in Trash',
    		'parent' => 'Parent Spanish/Yes Submission',
    	);
    		
    	$args = array(
    		'label' => 'Spanish/Yes Submissions',
    		'labels' => $labels,
    		'description' => '',
    		'public' => true,
    		'show_ui' => true,
    		'show_in_menu' => true,
    		'capability_type' => 'post',
    		'hierarchical' => true,
    		'rewrite' => array(
    			'slug' => ''
    		),
    		'query_var' => true,
    		'exclude_from_search' => false,
    		'supports' => array( 'author', 'title' ),
    		'show_in_menu'  =>	'edit.php?post_type=ey',
    		'menu_position' => 2
    	);
    		
    register_post_type( 'sy' , $args );
    }
    
    add_action('init', 'sn');
    function sn()
    {
    	$labels = array(
    		'all_items' => 'All Spanish/No Submissions',
    		'name' => 'Spanish/No Submission',
    		'singular_name' => 'Spanish/No Submission',
    		'menu_name' => 'Spanish/No Submission',
    		'add_new' => 'Spanish/No Submission',
    		'add_new_item' => 'Add New Spanish/No Submission',
    		'edit' => 'Edit',
    		'edit_item' => 'Edit Spanish/No Submission',
    		'new_item' => 'New Spanish/No Submission',
    		'view' => 'View Spanish/No Submission',
    		'view_item' => 'View Spanish/No Submission',
    		'search_items' => 'Search Spanish/No Submissions',
    		'not_found' => 'No Spanish/No Submission Found',
    		'not_found_in_trash' => 'No Spanish/No Submission Found in Trash',
    		'parent' => 'Parent Spanish/No Submission',
    	);
    		
    	$args = array(
    		'label' => 'Spanish/No Submissions',
    		'labels' => $labels,
    		'description' => '',
    		'public' => true,
    		'show_ui' => true,
    		'show_in_menu' => true,
    		'capability_type' => 'post',
    		'hierarchical' => true,
    		'rewrite' => array(
    			'slug' => ''
    		),
    		'query_var' => true,
    		'exclude_from_search' => false,
    		'supports' => array( 'author', 'title' ),
    		'show_in_menu'  =>	'edit.php?post_type=ey',
    		'menu_position' => 2
    	);
    		
    register_post_type( 'sn' , $args );
    }
    
    add_action( 'init', 'create_vbs_tax' );
    
    function create_vbs_tax() {
    	register_taxonomy(
    		'conferences',
    		'ey',
    		array(
    			'label' => __( 'Conferences' ),
    			'rewrite' => array( 'slug' => 'conferences' ),
    			'hierarchical' => true,
    			'menu_position' => 5
    		)
    	);
    }

    Any chance “‘show_in_menu’ => ‘edit.php?post_type=ey'” could be part of the issue?

  • Hi @brotsky_pixie

    The acf/save_post hook is executed every time a post or page is saved. That means that you can use only one function, but you need to make sure which post type you want to modify. Here’s an example how to do it in your case:

    //Auto add and update Title field for English/Yes form:
    function vbs_post_title_updater( $post_id ) {
        
        // list the post type you want to modify
        $post_types = array('en', 'ey');
        
        // get the current post type
        $current_post_type = get_post_type($post_id);
        
        // if current post type is not in the list, don't do anything
        if( !in_array($current_post_type, $post_types) ){
            return;
        }
        
        // Set the title for 'en' post type
        if( $current_post_type == 'en' ) {
            
            // get the church name
            $new_title_church_name = get_field('church_name', $post_id);
    
            // get the selected date and the current date
            $new_title_date = get_field('start_date', $post_id);
            $new_title_date = new DateTime($new_title_date);
            
            // set the title
            $new_title = $new_title_church_name . ' - ' . $new_title_date->format('M j, Y');
        
        // set the title for 'ey' post type
        } elseif ( $current_post_type == 'ey' ) {
            
            // get the church name and set it directly to the post title
            $new_title = get_field('church_name2', $post_id);
        }
        
        $new_slug = sanitize_title( $new_title );
    
        // create the update data holder
    	$vbs_ey_post = array();
    	$vbs_ey_post['ID'] = $post_id;
    	$vbs_ey_post['post_title'] = $new_title;
    	$vbs_ey_post['post_name'] = wp_strip_all_tags($new_slug);
    
        //Unhook function to prevent infitnite looping
    	remove_action('acf/save_post', 'vbs_post_title_updater', 20);
    
    	// Update the post into the database
    	wp_update_post( $vbs_ey_post );
    
    	//Rehook function to prevent infitnite looping
    	add_filter('acf/save_post', 'vbs_post_title_updater', 20);
    
    }
    // run after ACF saves the $_POST['fields'] data
    add_action('acf/save_post', 'vbs_post_title_updater', 20);

    If it shows any error message, please let me know the message.

    Hope this helps 🙂

  • This *feels* like it’s getting close. I’d started something similar that was doing pretty much exactly this. It’s still creating the posts in the backend though.

    I’d been doing the if statements using “church_name” and “church_name2” fields. Exactly the same results though. Yours, using the post type itself, is more elegant I think, though.

    The one thing from your code above that I changed was $vbs_ey_post to $vbs_post – and I kept it that way in both form pages as well.

    BUT, this is the error I wind up with: Warning: array_merge(): Argument #2 is not an array in /home/ccharacternew/public_html/childmin/wp-includes/post.php on line 3592

    Warning: Cannot modify header information – headers already sent by (output started at /home/path/wp-includes/post.php:3592) in /home/path/wp-includes/pluggable.php on line 1167

  • (my apologies…when I first responded, I wasn’t getting the errors. Then I realized I hadn’t copied the top portion of the code you’d provided. After adding that, I got the errors)

  • Ok. I’ve gotten rid of the error message (there was one $vbs_post_ey that I’d forgotten to change).

    BUT, now I’m getting the slug writing correctly, but it’s not including the post type in order to reference the correct single post template. In other words, for an ‘en’ submission it’s giving a path like this: http://www.website.com/stripped-slug instead of http://www.website.com/en/stripped-slug

    That said, it now works fine for the ‘ey’ post type. Not sure why it works for one but not the other…

  • Hi @brotsky_pixie

    Could you please share the code you used? Also, please don’t forget to remove the unused acf/save_post function (vbs_post_title_updater2). Also, you’re not supposed to use the ‘post_title’ option in the acf_form() arguments like this:

    'post_title' => wp_strip_all_tags($new_title2),

    The ‘post_title’ option will only receive false or true value. If you want to set it for the new post, you need to do it like this:

    'new_post'		=> array(
        'post_type'		=> 'en',
        'post_status'	=> 'publish'
        'post_title'	=> wp_strip_all_tags($new_title2),
    ),

    Or just remove it because the new title will be replaced later in the acf/save_post hook.

    Thanks 🙂

  • Functions.php

    //Auto add and update Title field for English/Yes & English/No forms:
    function vbs_post_title_updater( $post_id ) {
        
        // list the post type you want to modify
        $post_types = array('ey', 'en');
        
        // get the current post type
        $current_post_type = get_post_type($post_id);
        
        // if current post type is not in the list, don't do anything
        if( !in_array($current_post_type, $post_types) ){
            return;
        }
        
        // Set the title for 'ey' post type
        if( $current_post_type == 'ey' ) {
            
            // get the church name
            $new_title_church_name = get_field('church_name', $post_id);
    
            // get the selected date and the current date
            $new_title_date = get_field('start_date', $post_id);
            $new_title_date = new DateTime($new_title_date);
            
            // set the title
            $new_title = $new_title_church_name . ' Adventist Church - ' . $new_title_date->format('M j, Y');
        
        // set the title for 'en' post type
        } elseif ( $current_post_type == 'en' ) {
            
            // get the church name and set it directly to the post title
            $new_title = get_field('church_name2', $post_id) . ' Adventist Church';
        }
        
        $new_slug = sanitize_title( $new_title );
    
        // create the update data holder
    	$vbs_post = array();
    	$vbs_post['ID'] = $post_id;
    	$vbs_post['post_title'] = $new_title;
    	$vbs_post['post_name'] = wp_strip_all_tags($new_slug);
    
        //Unhook function to prevent infitnite looping
    	remove_action('acf/save_post', 'vbs_post_title_updater', 20);
    
    	// Update the post into the database
    	wp_update_post( $vbs_post );
    
    	//Rehook function to prevent infitnite looping
    	add_filter('acf/save_post', 'vbs_post_title_updater', 20);
    
    }
    // run after ACF saves the $_POST['fields'] data
    add_action('acf/save_post', 'vbs_post_title_updater', 20);

    EY form page

    $vbs_post = array(
    		'post_id'		=> 'new_post',
    		'post_title'	=> wp_strip_all_tags($new_title),
    		'post_content'	=> false,
    		'form' => true,
    		'new_post'		=> array(
    			'post_type'		=> 'ey',
    			'post_status'	=> 'publish'
    		),
    		'field_groups'       => array(2793),
    		'return'             => '%post_url%',
    		'submit_value'       => 'Submit VBS Event',
    		'updated_message'    => 'Saved!'
    	);
    	
    	acf_form( $vbs_post );

    EN form page

    $vbs_post = array(
    		'post_id'		=> 'new_post',
    		'post_title'	=> wp_strip_all_tags($new_title),
    		'post_content'	=> false,
    		'form' => true,
    		'new_post'		=> array(
    			'post_type'		=> 'en',
    			'post_status'	=> 'publish'
    		),
    		'field_groups'       => array(3052),
    		'return'             => '%post_url%',
    		'submit_value'       => 'Submit',
    		'updated_message'    => 'Saved!'
    	);
    	
    	acf_form( $vbs_post );

    I also just now tried without the “‘post_title’ => wp_strip_all_tags($new_title),” in the array for en, but it didn’t solve it.

    I don’t *think* I still have the errant acf/save_post you mention. But I concede that I simply may not be seeing it.

  • Hi @brotsky_pixie

    Could you please open a new ticket and provide the admin credentials to your staging/development site? You can open it here: https://support.advancedcustomfields.com/new-ticket. Don’t forget to include the URL to this thread and provide the locations where the code can be found on the site (backend and front-end).

    Thanks 🙂

Viewing 20 posts - 1 through 20 (of 20 total)

The topic ‘Frontend Form not populating right in backend’ is closed to new replies.