Advanced Custom Fields as Shortcodes

I use the WordPress plugin Advanced Custom Fields to simplify adding content to a site. I typically code the fields into a PHP page template but sometimes I’m not sure my customer is set on the layout of the page and need to leave it open ended if I need to style the page differently. However, I don’t want the customer to have to edit HTML or see it if possible.

A solution I came up with was to add the fields as shortcodes to the main WordPress content editor but disable the content editor for the Editor role. The Admin user role can still see the content editor to edit HTML and field shortcodes all while the Editor role gets simple text inputs. This is actually really simple to implement into a theme.

Step One: Action Hook

// Remove Content Editor for content type: Page, user role: Editor

if( current_user_can('editor') ) {
  add_action('init', 'my_remove_editor_from_post_type');
  function my_remove_editor_from_post_type() {
       remove_post_type_support( 'page', 'editor' );
  }
}

Add this to your theme’s function.php file.
In order to check for other user roles: http://wp-snippets.com/check-user-role/

Step Two: Shortcodes

<!-- ACF Fields -->

<h3></h3>
<p></p>
<p><a href=""></a></p>

Add the shortcodes into the content editor. Shortcode Documentation

Performance

I wanted to find out how many more queries to the database this was going to add, how fast it would execute, and is it worth it. I did a quick test with the following content to find out what was happening.

acf-example2

H3 paragraph heading, one paragraph of content, and a link.

The Results

  1. 35 queries in 0.669 seconds with HTML typed into the content editor
  2. 40 queries in 0.699 seconds with PHP coded ACF fields
  3. 40 queries in 0.728 seconds with shortcodes in the content editor

This approach works pretty well but could probably use some kind of conditional statement in the action hook to only allow the content editor to be removed from pages in which ACF is implemented. Otherwise the main content editor will be removed from all the pages within the Editor user’s role. There may also be a plugin that solves this too.