Simplifying Content Management with Advanced Custom Fields

Published Jan 12, 2017Last updated Jan 18, 2017
Simplifying Content Management with Advanced Custom Fields

The Advanced Custom Fields plugin (ACF) has become an essential tool in how I set up a publishing workflow for self-service clients who aren’t proficient in HTML. In my early days of WordPress development, I would provide my clients with code snippets and documentation that explained how to apply them to portions of their content that required specific styling. This would inevitably result in emails requesting technical support when the code was not properly formatted; one missing closing div tag and the whole page would break.

For this tutorial we will build a “My Favorite Things” blog by setting up custom field groups for each category, then add code to the single post template to display custom field data.

What You Will Need

Step 1: Setting Up the Child Theme

  • In your themes directory, create a folder named "twentyseventeen-child"
  • Create a new file named "styles.css" with the following content:
/*
Theme Name: Twenty Seventeen with Custom Fields
Theme URI: https://wordpress.org/themes/twentyseventeen/
Template: twentyseventeen
Description: Twenty Seventeen with Advanced Custom Fields additions
Version: 1.0
*/
  • Create a new file named "functions.php" with the following content:
<?php
/**
 * Twenty Seventeen with Advanced Custom Fields functions and definitions
 */

/**
 * Include parent theme styles
 */
add_action( 'wp_enqueue_scripts', 'enqueue_parent_styles' );

function enqueue_parent_styles() {
   wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );
}

Now go to your WordPress Dashboard and select Appearance > Themes from the menu. You should see your new child theme appear in the list, go ahead and activate it.

Step 2: Add Post Categories

  • From the Dashboard, go to Posts > Categories.
  • Add two new categories: "Music" and "Books"

Step 3: Create Custom Field Groups

A. Music Field Group

For any posts categorized as "Music", we want the option to embed a sound and video player featuring work by the artist in the post. (Make sure you have ACF installed and activated!)

  • From the Dashboard, go to the "Custom Fields" menu. You should see an empty table of Field Groups, click "Add New" at the top of the page.
  • Name the group "Music"
  • Click on the blue "+ Add Field" button
  • Enter "Audio Embed" for the field label
  • The Field Name should auto populate with "audio_embed", so you can leave that as is
  • Leave the Field Type set to the default option, "Text"
  • In Field Instructions, add "Paste HTML code for the audio embed"
  • Leave all the remaining settings as they are, scroll down to the end of the form and click the "Close Field" button to collapse the "Audio Embed" field options.
  • Click the "+ Add Field" button again
  • Enter "Video Embed" for the field label
  • Add "Paste HTML code for the video embed" to the Field Instructions.
  • Click the "Close Field" button to collapse the "Video Embed" field options
  • Now scroll down to the next panel labeled "Location". This is where we define the criteria that dictates when this field group will display.
  • Select "Post Category" from the first dropdown.
  • The last dropdown should populate with a list of the categories we added. Select "Music"
  • Your field group settings should look like this:

Content Management

  • Scroll back up to the top of the page and click the "Publish" button

B. Books Field Group

For any posts categorized as "Books," we will want to display the author name, some of our favorite quotes, and the year of publication.

  • Add a new Field Group titled "Books"
  • The first field will be named "Author Name".
  • Go to the "Required?" setting and set it to "Yes"
  • You can leave all the default settings as is and click the "+Add Field" button
  • The second field we'll name "Favorite Quotes" and set the Field Type to "Textarea." This will make the field multi-line on post pages
  • Add one more field named "Publication Year," and set the Field Type to "Number." This will restrict the field to only accept numbers
  • In the Location panel, we'll select "Post Category" again, but this time select "Books" in the last dropdown
  • Once you collapse all the fields, this is how your group should look:

Content Management

  • Scroll back up to the top of the page and click the "Publish" button

Our last field group will be all be simple Text fields where we can add links to the artist's external site and social platforms.

  • Add a new Field Group titled "Artist Links"
  • Create new fields with the following names "Artist Website," "Artist Soundcloud," "Artist Spotify," "Artist Twitter," "Artist Instagram," and "Artist Youtube"
  • In the Location panel, select "Post Category" in the first dropdown and "Music" in the last
  • At the bottom of the panel, click the "Add rule group" below "or"
  • Select "Post Category" in the first dropdown and "Books" in the last
  • Scroll down to the Options panel, and change the "Order No." from 0 to 1
  • Your field group settings should look like this:

Content Management

  • Scroll back up to the top of the page and click the "Publish" button

Step 4: Add Some Posts

Go to Posts > Add New, you should see the standard WordPress post fields: Title & Content. You'll notice that none of the custom fields we just created are visible. However, if you check the "Books" or "Music" categories, you'll see the appropriate fields appear below the content.

We'll need some test content in order to setup and test our templates, so create a couple of posts for our two categories. I am going to use the Musician's name for the title of my "Music" posts, and the book's title for "Book" posts. I use the primary content field for my commentary on the musician or book. The rest of the fields should be pretty self-explanatory. Most authors won't have Soundcloud, Spotify, or possibly any social media links, but none of those fields are required.

Here's what my Music post looks like all filled out:

Content Management

And a Book post:

Content Management

Step 5: Modifying Templates to Display the Data

Let's start by adding the post content template to our child theme. Go into the parent theme's folder and copy the file "template-parts/post/content.php" over to your child theme, preserving the directory structure. Your theme folder should look like this now:

Child theme files


get_field vs the_field

To add in our ACF data, we'll be utilizing two functions: get_field and the_field. It's important to remember the distinction between the two:

  • get_ will simply check for and retrieve the field data; whereas
  • the_ will check for the data and print it.

It's similar to how Wordpress works with functions such as get_the_title vs the_title.

**The important thing to remember is not to use the_field inside conditional statements, or else the data will be printed out every time it returns true. **


Adding author_name to Book Posts

Open up the content.php in your preferred code editor. Let's start by adding the author's name below the title of posts in the "Book" category. Find the closing </header> tag and insert this code:

<?php if(has_category('books')): ?>
  <div class="author-name">by <?php the_field('author_name'); ?></div>
<?php endif; ?>

Adding publication_year to Book Posts

Next, let's add some code right after the opening div containing the post content to display the book's publication year:

<div class="entry-content">
  <?php if(has_category('books')): ?>
  <div class="publication-date"><strong>Published:</strong> <?php the_field('publication_year'); ?></div>
  <?php endif; ?>

Adding Media Embeds to Music Posts

In this next block of code, we'll be checking to see if the post is in the "Music" category and if the template is currently being called from a single post. The reason for the second condition is that we don't want the embeds to display while viewing the blog index or other archival views such as category, tag, or date archives.

Then inside of that first condition, we will use get_field to check if any data exists before displaying an H3 label for the embed, followed by the embed code.

<?php
if(has_category('music') && is_single()):
  
  if(get_field('audio_embed')):
  ?>
  <h3>Listen:</h3>
  <?php
    the_field('audio_embed');
  endif;

  if(get_field('video_embed')):
  ?>
  <h3>Watch:</h3>
  <?php
    the_field('video_embed');
  endif;

endif;
?>

Adding favorite_quotes to Book Posts

We'll now add code similar to the media embeds on Music posts, but this time to display our favorite quotes:

<?php
if(has_category('books') && is_single()):
  if(get_field('favorite_quotes')):
    ?>
    <h3>Favorite Quotations:</h3>
    <blockquote>
    <?php
    the_field('favorite_quotes');
    ?>
    </blockquote>
    <?php
  endif;
endif;
?>

We'll go through this next block of code a few lines at a time. First we will check that a post is assigned to either "Books" or "Music," and then that the template is currently being called from a single post.

if(has_category(['books','music']) && is_single()):

Next we are going to check if there is data in any one of our link fields:

if(get_field('artist_website') || get_field('artist_soundcloud') || get_field('artist_spotify') || get_field('artist_twitter') || get_field('artist_instagram') || get_field('artist_youtube')):

Within that second condition is where we will start to display our external links. First with a header to label the links:

<h3>Follow this artist:</h3>

Then we'll start an unordered list tag, wrapped in a div container. I'm assigning the div a custom class of "artist-links", and using the "social-navigation" class which is defined in the parent theme. This will convert the subsequent list items into icons if I follow the same markup style that was already written into the theme for the blog's social links.

<div class="artist-links social-navigation">
  <ul>

For each link type, I will first check to see if data exists using get_field, then inject the link into the anchor tag using the_field, and display the appropriate icon using a function provided by Twenty Seventeen:

<?php if(get_field('artist_website')): ?>
  <li>
    <a href="<?php the_field('artist_website'); ?>" target="_blank" title="Official Website">
    <?php echo twentyseventeen_get_svg(array('icon'=>'chain')); ?>
    </a>
  </li>
<?php endif; ?>

Here is the full block of code for the artist links:

  <?php
  if(has_category(['books','music']) && is_single()):
    if(get_field('artist_website') || get_field('artist_soundcloud') || get_field('artist_spotify') || get_field('artist_twitter') || get_field('artist_instagram') || get_field('artist_youtube')):
      ?>
    <h3>Follow this artist:</h3>
    <div class="artist-links social-navigation">
      <ul>
      <?php if(get_field('artist_website')): ?>
        <li>
          <a href="<?php the_field('artist_website'); ?>" target="_blank" title="Official Website">
          <?php echo twentyseventeen_get_svg(array('icon'=>'chain')); ?>
          </a>
        </li>
      <?php endif; ?>
      <?php if(get_field('artist_soundcloud')): ?>
        <li><a href="<?php the_field('artist_soundcloud'); ?>" target="_blank" title="Soundcloud">
          <?php echo twentyseventeen_get_svg(array('icon'=>'soundcloud')); ?>
          </a>
        </li>
      <?php endif; ?>
      <?php if(get_field('artist_spotify')): ?>
        <li><a href="<?php the_field('artist_spotify'); ?>" target="_blank" title="Spotify">
          <?php echo twentyseventeen_get_svg(array('icon'=>'spotify')); ?>
          </a>
        </li>
      <?php endif; ?>
      <?php if(get_field('artist_youtube')): ?>
        <li><a href="<?php the_field('artist_youtube'); ?>" target="_blank" title="Youtube">
          <?php echo twentyseventeen_get_svg(array('icon'=>'youtube')); ?>
          </a>
        </li>
      <?php endif; ?>
      <?php if(get_field('artist_instagram')): ?>
        <li><a href="<?php the_field('artist_instagram'); ?>" target="_blank" title="Instagram">
          <?php echo twentyseventeen_get_svg(array('icon'=>'instagram')); ?>
          </a>
        </li>
      <?php endif; ?>
      <?php if(get_field('artist_twitter')): ?>
        <li><a href="<?php the_field('artist_twitter'); ?>" target="_blank" title="Twitter">
          <?php echo twentyseventeen_get_svg(array('icon'=>'twitter')); ?>
          </a>
        </li>
      <?php endif; ?>
      </ul>
    </div>
      <?php
    endif;
  endif;
?>

Step 6: Styling the Data

Once you see your field data displaying, we can move to the final step of adding CSS. I wanted to add a border to the bottom of my publication year, the social-navigation class was defaulting to about 50% width, and my icons were showing up as grey on grey. So I added these following to styles.css to address these issues:

/* Book Post Custom Styles*/
.publication-date{
  border-bottom:1px dotted #999;
  margin-bottom: 1em;
}

/* Social Share Links for artists*/
.artist-links.social-navigation {
  width:100%;
}
.artist-links.social-navigation a {
  color:#fff;
}

Wrapping up

You can see my final results here, and download the customized child theme here.

Discover and read more posts from Brian Douglas
get started
Enjoy this post?

Leave a like and comment for Brian

Be the first to share your opinion

Get curated posts in your inbox

Read more posts to become a better developer