How to add Advanced Custom Fields frontend form with shortcode

ACF front-end form shortcode

Code Snippet for Advanced Custom Fields

Advanced Custom Fields (ACF) is a powerful tool to add custom fields to your pages, posts, and custom post types in WordPress. It’s primarily geared towards adding extra fields in the admin area and display the data on the frontend. It can also be used to display a form on the frontend – as explained by the plug-in – using the function ‘acf_form‘.

That function should be placed in a template file, e.g. ‘page-myform.php’.

Often you don’t want that form in a template file, but rather in an exact place within your content. For that you’ll need a shortcode. Yes, we know there are plugins to directly insert php code in your content, but for security reasons that’s to be avoided at all cost. Just don’t do it!

So, how to add an ACF form to the content of your page or post using a shortcode? That’s not so obvious and, to be honest, poorly explained by ACF itself.

It’s not enough to simply put that code used for a template file within the ‘add shortcode‘ function. It will not work. Why? Because ACF outputs the form when the shortcode is run. However, what you need is the value returned. To achieve that, you’ll have to add a bit of extra code in order to use a PHP output buffer.

Let’s say you have a frontend form allowing guest visitors to add content to your website in the default post type ‘Post’.

To have that form appear at the position you want using a shortcode, the function looks like this:


add_shortcode( 'cambodesign-form', 'cambodesign_new' );
function cambodesign_new() {
ob_start();
    acf_form(array(
    'post_id'		=> 'new_post',
    'field_groups'      => array(123), // ACF Field Groups ID('s)
    'form'              => true,
    'new_post'		=> array(
        'post_type'	=> 'post', // You can change to a custom post type
        'post_status'	=> 'pending',
    ),
    'submit_value' => __("Submit New Post", 'acf')
));
}

$html = ob_get_contents(); 
ob_end_clean();
return $html;

}

Note the additions in the code that you do not need in a template file. The full code above goes into your child theme’s ‘functions.php’ file, or in a plug-in called Code Snippets. The shortcode to use in your content area is as simple as this: [cambodesign-form]

By the way, this works for both ACF Free and ACF Pro.

And how do you restrict posting new content to logged in users (i.e. users you ‘know’?). That’s another post, soon to be published here. But in the meantime, see ‘post_status’ in the code above. It’s set to ‘pending’, so that a new post is not published right away, you have to manually approve it yourself before it’s published on your website.

Please click on the Share links below if you find this tip useful. ThankĀ  you.