WordPress
Article

Getting Started with Advanced Custom Fields (ACF)

By James Steinbach

Why Use Custom Fields?

I can’t begin to express how blown my mind was when I got started with Advanced Custom Fields (ACF). When I started using WordPress, I figured out how to bend Posts and Pages to do a whole lot more than they should have. I’d give clients very specific instructions for using Categories and Parent Pages in convoluted ways. Then I discovered custom post types and my instructions got a whole lot simpler.

But even with separate post types, not every piece of content fits neatly into a title+content+excerpt+thumbnail mold. Events require start dates and times. Employees often need email addresses or titles. Products might have prices, color variations or sizes. All these content types push WordPress beyond simple custom post types.

What About Plugins?

One solution to this is to find a plugin for each and every kind of custom content you need. Install WooCommerce for products, The Events Calendar for events, Meet My Team for employees, Soliloquy for slides, or WPP for portfolio items. That works for a lot of people: it’s faster to develop that way at first.

However, I’m not a fan of plugin smorgasbords for two reasons. First, every plugin you add affects site speed (hardly any speed it up!). Chances are high that every content type plugin you add will add its own JS and CSS files to the front end. You can literally watch your Page Speed score plummet as you add those plugins. Second, most plugins you use will look different from your theme (with the exception of premium themes that are “compatible” with major plugins). This will have one of two negative results: either your site will look like it’s been patched together from three or four plugins, or you’ll spend a ton of time overriding plugin CSS to make plugin content types look like they belongs in your theme.

ACF Field Types

Advanced Custom Fields (ACF) provides a way to attach almost any kind of custom field imaginable to your post types.

Included Field Types

The ACF plugin comes with more than 20 field types by default:

Custom field types

  • Text: Single line text field, optional HTML support, character limit
  • Text Area: Multi-line text field, optional HTML support, character limit
  • Number: Number, min/max values
  • Email: Validates email input
  • Password: Masks text for password input
  • Wysiwyg Editor: Optional WP media insertion, basic/full editor buttons
  • Image: Upload image or select from WP library, returns object, url or ID
  • File: Upload file or select from WP library, returns object, url or ID
  • Select: Provide options in drop-down, supports multi-select
  • Checkbox: Allow selection of multiple items in checkbox list
  • Radio Button: Allow selection of single item from radio button list
  • True / False: Simple true / false selector
  • Page Link: Returns URL of any post or page, can be limited to specific post types
  • Post Object: Returns WP object of any post or page, can be limited to specific post types or taxonomies
  • Relationship: Same as post object, but with improved interface and drag-drop reordering
  • Taxonomy: Returns object or ID for one or more taxonomy terms, can be limited to tags, categories or custom taxonomies
  • User: Select one or more users, can be limited by role
  • Google Map: Set lat/long center, zoom level, and width
  • Date Picker: Select calendar date, return formatted date string
  • Color Picker: Select hexadecimal color
  • Message: No options, leave a message for users
  • Tab: Collect following fields into a tab interface

Free Add-on Fields

The WordPress plugin repo and the ACF add-ons page have a number of helpful add-on plugins for ACF. These plugins allow users to select a menu, select a sidebar select a Gravity Form, collapse complex field groups and import spreadsheets.

Paid Add-on Fields

There are a few premium ACF add-ons that are very useful. Most cost around $25 and are well worth it, in my opinion.

Repeater: The ACF Repeater Field allows users to develop complex layouts with any number of fields. For instance, a repeater field could contain a Text field, an Image field and a WYSIWYG field, allowing users to create a list of “Services” with icon, title and description.

Flexible Content: The ACF Flexible Content Field allows users to set up multiple layouts (each made of multiple fields) which can then be selected and used in any order on the page. See this Snow Fall tutorial for an example of Flexible Content fields in action.

Options Page: The ACF Options Page add-on allows developers to create custom options pages in the Dashboard, then attach any set of custom fields to those pages. This is quite useful for collecting site-wide data, such as company address, social media links, phone number or theme color options.

Attaching Field Groups to Content

ACF Field Groups can be attached to content by any criteria: post type, page template, parent page, post category or tag, taxonomies themselves, media, and users.

Setting field group locations

On the Edit page for the content that the field group is attached to, any pieces of the default WordPress admin can be hidden (Editor, Featured Image, Slug, Author, etc), and the Field Group can be place below the Title, below the Editor, or in the right column.

Using ACF Fields in Templates

ACF provides several useful PHP functions for including custom field data in WordPress template files. The ACF Documentation pages have a great deal of useful information. The following are some of the most common functions used.

get_field()

The get_field('field_name', $post->ID, 'option') function returns the formatted contents of the custom field whose name is passed as a parameter. A post ID parameter is optional: if this function is being used outside the loop or to access fields from another post or page, the ID would be necessary. If the field is on an Options Page, include the 'option' inside this function.

Since this function returns data, it can be assigned to a variable, or displayed with print or echo.

if ( get_field('sub_title') ) :
	print '<h2 class="sub-title">'.get_field('sub_title').'</h2>;
endif;

the_field()

The the_field() function echos the contents of the field, formatted according to the parameters in the Custom Field Group admin area. It can take the same $post->ID and 'option' parameters as get_field(). It’s basically the same thing as echo get_field().

if ( get_field('staff_image') ) :
	the_field('staff_image');
endif;

Subfields

If the custom field is in a Repeater Field or Flexible Content Field, use get_sub_field() and the_sub_field() instead. The $post-ID and 'option' parameters work the same way.

Looping Through Fields

To loop through all the rows in a Repeater Field or Flexible Content Field, use have_rows('field_name', $post->ID, 'option') and the_row(). These functions work very similarly to the WordPress loop functions:

if ( have_rows('image_rows') ) :
	while ( have_rows('image_rows') ) : the_row();
		the_sub_field('row_icon');
		the_sub_field('row_title');
		the_sub_field('row_text');
	endwhile;
endif;

The Flexible Content Field has multiple layouts. The function get_row_layout() returns the name of the layout in use at that iteration of the loop.

Conclusion

When it comes to using Advanced Custom Fields to make WordPress a highly-configurable CMS, the sky is the limit. These fields can be used to create precise custom content input and style to create complex custom layouts. Share one of your best ACF-enabled projects in the comments, or ask a question about using these fields in one of your sites.

  • http://nyasro.com/ Nyasro

    What a co-incidence :)
    I just found “acf” text one of wordpress theme but didn’t know what it is.
    And you posted article of ACF.
    Thank you very much.
    It helped me to boost my knowledge.

  • Oleg
    • http://jamessteinbach.com/ James Steinbach

      Types is also fantastic: I use both. (See: http://www.sitepoint.com/custom-post-types-take-wordpress-beyond-blogging/ ) Sometimes I can create all the custom fields I need with the Types fields interface, but not always. ACF has some more advanced features (character limits) and some more powerful field types (post object) that I need for many projects.

  • http://ChiefAlchemist.com/ Mark Simchock

    I was just considering ACF again last night.

    Am I the only one who looks at get_field() and worries. I mean even acf_get_field or get_field_acf() would make a lot more sense. Or make it status and ACF::get_field() would probably be even smarter.

    I’d also suggest that

    if ( get_field(‘staff_image’) ) :
    the_field(‘staff_image’);
    endif;

    could be shorted into a single function that checks AND if necessary echos, else does nothing.

    I’ll keep looking but I’m thinking its time to update my class(es) for form elements.

  • http://www.complet-it.com/ Mincă Daniel Andrei

    Thanks for the very useful article ! I was struggling to get them done by ‘stealing’ from the core file, I can say that now my work is 70% done with this useful tutorial :D

  • StNick

    I love the ACF plugin but the guy behind all the stuff is kind of a big ****. Don’t expect any useful support from him. Anything vastly different than ‘check the (badly written) documentation’ cannot be expected from this man.

  • YemSalat

    I cant understand how these can be useful. Can’t you already do all that with wp api?

  • Chris

    This is helpful I just started using ACF help me understand, are you saying that with every Custom Field you add in the admin, there is a corresponding code that goes in the respective wp core file? I.E. adding a Gallery to a post, then adding Gallery field to post php? Just trying to get this thing to work and to be hones the documentation on the ACF site is a bit confusing.

  • http://jamessteinbach.com/ James Steinbach

    Quick update to this post: ACF recently changed their plugin model. There’s still a free version like the free version described above, but instead of buying premium extensions, you’d buy a Pro version of the plugin that includes the premium field types: http://www.advancedcustomfields.com/pro

  • Roshan

    I am using ACF for more than 3 years, i started in from 1st version, soo far this is one of the best plugins for wordpress available right now, about the documentation ACF site is providing almost everything you need to develop the site, with this plugin you need to depend on standard galleries or fields, you can create your own by page or by post.

    It’s great if we can find out how to use same features with a plugin, cuz we never know when will this end. I have done soo many projects using this plugin, soo far i face few bugs due expire versions.

  • http://www.pepperstreet.de/ pepperstreet

    Thanks for your efforts and the article about ACF. Nice write-up to get a quick overview!

  • Brijesh Maurya

    thanks for this … But can u teach how to use this Pluggin from basic to advanced…

  • Brad Taylor

    @jdsteinbach:disqus – What about using them together? I’m currently doing some testing in a MU environment with ‘Types’ and ‘ACF’. Trying to find limitations and things that do no work seamlessly.

    • http://jamessteinbach.com/ James Steinbach

      I actually use them together on almost every project. I don’t use the custom fields features in the Types plugin (just its post types & taxonomy sections); I use ACF for custom fields and everything’s worked fine for me so far.

      • Brad Taylor

        Nice! What about conditional display and [wpv-if] – any usage there? I want to display a content template with ‘Views’ for a custom post type, but only if certain ACF fields are used/filled. I don’t have access to functions.php so I’d need an out of the box solution.

        Example : ACF checkbox is selected, then display a portion from template. If not display something else.

        What do you use to capture phone numbers – ‘text’ or ‘number’?

        • http://jamessteinbach.com/ James Steinbach

          I’m afraid I can’t answer the Views-related question – I’ve never used that plugin. I write all the conditional logic like that directly in my theme template files.

          For a phone number, I’d probably use the text field type. Number is meant for a single integer and browsers that support that HTML5 field type will treat it as such, not allowing hyphens or parentheses.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Instant Website Review

Use Woorank to analyze and optimize your website to improve your website to improve your ranking!

Run a review to see how your site can improve across 70+ metrics!

Get the latest in WordPress, once a week, for free.