ACF Frontend Form – Append New Post ID To Return URL When Creating Post

About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.

ACF Frontend Form – Append New Post ID To Return URL When Creating Post

Okay – this one kind of annoyed me to be honest. You know those late afternoons when your brain is already shot? But you refuse to quit working while there is still an unsolved problem on your desk. This was my exact thought process last week and I literally could not leave my office until I resolved this.

The issue: I am leveraging the ACF form to create a frontend post submission. I’ve done this many times but apparently I’ve never needed to retrieve the post ID that the form created after submission. While I thought this would be simple, it was actually a bit more difficult to figure out. Here’s what I did:

First, on my actual array of options for the form, I defined the return URL:

'return' => get_home_url() . '/redirect-url/%%post_id%%',

Very important, notice the ‘%%post_id%%’ appended to the end of the redirect URL. If this is present, we are going to swap this for the post ID in the URL.

Next, we have the function that is going to go in our functions.php file, it is:

//Add Post ID
function my_save_func($post_id) {
	$returnurl = $GLOBALS['acf_form']['return'];
	if (strpos($returnurl, '%%post_id%%') !== false) {
		$returnurl = str_replace("%%post_id%%", "", $returnurl);
		$returnurl = add_query_arg( 'id', $post_id, $returnurl );
		$GLOBALS['acf_form']['return'] = $returnurl;
add_action('acf/save_post', 'my_save_func', 20, 1912);

What this does it checks the return URL for the value of %%post_id%%. If it finds it, it removes %%post_id%% and then using the native add_query_arg found in WordPress, it appends the post_id to the end of the return URL. Pretty nifty huh? Hopefully this saves somebody a headache.

Share Your Thoughts

Leave a Reply

Your email address will not be published.

Related Stuff You Might Like

WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!