Chapter 5

Working with Custom Fields

IN THIS CHAPTER

Check Understanding what Custom Fields can do for you

Check Working with the Custom Fields interface

Check Adding custom field codes to your templates

Check Using custom fields in a variety of ways

In Book 4, Chapter 1, I discuss all the elements you can add to your blog posts and pages when you publish them. By default, WordPress allows you to give your posts and pages titles and content, to categorize and tag posts, to select a date and time for publishing, and to control the discussion options on a per-post or per-page basis.

Sometimes, however, you may want to add extra items to your posts — items you may not want to add to every post, necessarily, but that you add often enough to make manually adding them each time you publish a nuisance. These items can include a multitude of things, from telling your readers your current mood to what you’re currently listening to or reading — pretty much anything you can think of.

WordPress gives you the ability to create and add metadata (additional data that can be added to define you and your post) to your posts by using a feature called Custom Fields. In this chapter, I go through Custom Fields in depth by explaining what they are and how to implement them, as well as offering some cool ideas for using Custom Fields on your site.

Understanding Custom Fields

A WordPress template can contain static pieces of data that you can count on to appear on your site. These static items include elements such as the post title, the content, the date, and so on. But what if you want more? Suppose that you write a weekly book review on your site and want to include a listing of recent reviews and accompanying thumbnails of the books. Through the use of Custom Fields, you can do all that without having to retype the list each time you do a review.

Remember You can add thousands of autoformatted pieces of data (such as book reviews or movie reviews) by adding Custom Fields to your WordPress site. Okay, thousands of Custom Fields would be pretty difficult, if not impossible, to manage; my point here is that the Custom Fields feature doesn’t limit the number of fields you can add to your site.

You create Custom Fields on a per-post or per-page basis, which means that you can create an unlimited amount of them and add them only to certain posts. They help you create extra data for your posts and pages by using the Custom Fields interface, which is covered in the following section.

So what can you do with Custom Fields? Really, the only right answer is this: anything you want. Your imagination is your only limit when it comes to the different types of data you can add to your posts by using Custom Fields. Custom Fields allow you the flexibility of defining certain pieces of data for each post.

To use Custom Fields, you do need a bit of knowledge about how to navigate WordPress theme templates because you have to insert a WordPress function tag, with specific parameters, into the body of the template file. Book 6 takes you through all the information you need to understand WordPress themes, templates, and template tags, so you may want to hit that minibook before you attempt to apply what I discuss in the rest of this chapter. If you’re already comfortable and familiar with WordPress templates and tags, you probably won’t have any trouble with this chapter at all.

Exploring the Custom Fields Interface

The Custom Fields interface isn’t enabled by default on the Edit Post or Edit Page screens in your Dashboard; you have to enable it first by clicking the Show More Tools & Options icon in the top-right corner of the Edit Post screen. Clicking that icon displays a drop-down menu. Click the Options link to open a small window labeled Options (see Figure 5-1). Click the check box to the left of the Custom Fields label and then close the Options window by clicking the small X in the top-right corner.

Screenshot of the Edit Post screen of the WordPress Dashboard to add the Custom Fields interface by clicking on a drop-down menu.

FIGURE 5-1: Add the Custom Fields interface to the Edit Post screen.

With the Custom Fields interface displayed on the Edit Post screen, you see that it contains two text boxes:

  • Name (also known as the Key): You assign a name to the Custom Field you’re planning to use. The name needs to be unique because it’s used in the template tag that you can read about in “Adding Custom Fields to Your Template File” later in this chapter. Figure 5-2 shows a Custom Field with the name mood.
  • Value: You assign a value to the Custom Field name and displayed in your blog post on your site if you use the template tag (see “Adding Custom Fields to Your Template File” later in this chapter). In Figure 5-2, the value assigned to the mood (the Custom Field name) is Happy.
Screenshot of the Edit Post screen of the WordPress Dashboard displaying a Custom Field that has a name and value assigned.

FIGURE 5-2: A Custom Field that has a name and value assigned.

Simply fill out the Name and Value text boxes and then click the Add Custom Field button to add the data to your post or page. Figure 5-2 shows a Custom Field that I added to my post with the Name of mood and with the assigned value Happy. In “Adding Custom Fields to Your Template File” later in this chapter, I show you the template tag you need to add to your WordPress theme template to display this Custom Field, which appears in my post like this: My Current Mood is: Happy. In Figure 5-3, the Custom Field appears at the beginning of my post.

Screenshot displaying the Custom Fields output in a published post in the blog of a person.

FIGURE 5-3: Custom Field output in a published post.

You can add multiple Custom Fields to one post. To do so, simply add the name and the value of the Custom Field in the appropriate text boxes on the Edit Post screen; then click the Add Custom Field button to assign the data to your post. Do this for each Custom Field you want to add to your post.

Tip After you add a particular Custom Field (such as the mood Custom Field in Figure 5-2), you can always add it to future posts, so you can make a post tomorrow and use the mood Custom Field to assign a different value to it. If tomorrow you assign the value Sad, your post displays My Current Mood is: Sad. You can easily use just that one Custom Field on subsequent posts and have each post display a different value.

You can access your Custom Fields from the drop-down menu below the Name field. You can easily select a Custom Field again and assign a new value to it for future posts because WordPress saves that Custom Field Key, assuming that you may want to use it again sometime in the future.

Technical stuff Custom Fields are considered to be extra data, separate from the post content itself, for your posts. WordPress refers to Custom Fields as metadata. The Custom Field name and value get stored in the database in the wp_postmeta table, which keeps track of which names and values are assigned to each post. See Book 2, Chapter 4 for more information about the WordPress database structure and organization of data.

Remember You can find a Custom Fields module on the Edit Post screen of the Dashboard as well, so you can add Custom Fields to your posts or pages as needed.

Adding Custom Fields to Your Template File

If you followed along in the preceding sections and added the mood Custom Field to your site, notice that the data didn't appear on your site the way it did on mine. To get the data to display properly, you must open the template files and dig into the code a little bit. If the idea of digging into the code of your template files intimidates you, you can put this section aside and read up on WordPress themes, template files, and template tags in Book 6.

You can add Custom Fields to your templates in several ways to display the output of the fields you’ve set. The easiest way involves using the get_post_meta(); template tag function, which looks like this:

<?php
$key="NAME";
echo get_post_meta( $post->ID, $key, true );
?>

Here’s how that function breaks down:

  • <?php: Starts the PHP function. Every template tag or function needs to start PHP with <?php. You can read more about basic PHP in Book 2, Chapter 3.
  • $key="NAME";: Defines the name of the key that you want to appear. You define the name when you add the Custom Field to your post.
  • echo get_post_meta: Grabs the Custom Field value from the database and displays it on your site.
  • $post->ID,: A parameter of the get_post_meta function that dynamically defines the specific ID of the post being displayed so that WordPress knows which metadata to display.
  • $key,: A parameter of the get_post_meta function that gets the value of the Custom Field based on the name, as defined in the $key="NAME"; setting earlier in the code string.
  • true);: A parameter of the get_post_meta function that tells WordPress to return a single result rather than multiple results. (By default, this parameter is set to true; typically, you don't change it unless you’re using multiple definitions in the Value setting of your Custom Field.)
  • ?>: Ends the PHP function.

Based on the preceding code, to make the mood Custom Field example, you define the key name as mood (replace the NAME in the preceding code with the word mood). It looks like this:

<?php
$key="mood";
echo get_post_meta( $post->ID, $key, true );
?>

The part of the function that says $key="mood"; tells WordPress to return the value for the Custom Field with the Name field of mood.

Entering the code in the template file

So that you can see how to enter the code in your template file, I use the default WordPress theme called Twenty Nineteen in this section. If you're using a different theme (thousands of WordPress themes are available), you need to adapt these instructions to your particular theme.

For the purposes of this chapter, I’m using the Twenty Nineteen theme, which is the default theme and is included in every new installation of WordPress. You should have installed WordPress by now, so chances are good that you already have the Twenty Nineteen theme.

Warning Normally, when I practice coding on a website, I use a code repository with version control so that I can keep automatic backups of my template files; this practice allows me to easily and quickly reverse any changes I’ve made in the files if I’ve made a mistake or want to undo something I’ve done. The use of a code repository with version control is a topic for a whole other book. (You could try Professional Git by Brent Laster from Wrox Publishing.) For the purposes of the coding exercises in the book, you’ll be downloading, editing and re-uploading the files via Secure FTP (SFTP), so I strongly recommend that you keep a copy of the files on your computer in a different folder, safe from any alterations. That way, you can restore the original files to your web server if needed.

Follow these steps to add the template tag to your theme, along with a little HTML code to make it look nice. (These steps assume that you’ve already added the mood Custom Field to your blog post and assigned a value to it.)

  1. Log in to your web server via SFTP.

    For details on connecting to your website via SFTP, refer to Book 2, Chapter 2.

  2. Navigate to the Twenty Nineteen theme folder.

    On your web server, that folder is /wp-content/themes/twentynineteen/.

  3. Locate the content-single.php file.

    This file is located on your web server at wp-content/themes/twentynineteen/template-parts/content/.

  4. Download the content-single.php file, and open it in a text editor.

    You may use any text editor you prefer, such as Notepad (PC) or TextEdit (Mac).

  5. Scroll down to locate the HTML tag that looks like this: <div class="entry-content">.

    This HTML tag appears on line 21 of the content-single.php file.

  6. On the new line directly below the line in step 5, type this:

    <p>My Current Mood is:

    <p> open the HTML tag for a paragraph, followed by the words to display in your template (My Current Mood is:). When you're done typing, press Enter to start a new line.

  7. On the newly created line, type the PHP that makes the Custom Field work:

    <php
    $key="mood";
    echo get_post_meta( $post->ID, $key, true );
    ?>

  8. Press Enter to create a new line, and type the </p> HTML tag.

    This code closes the HTML paragraph tag you opened in step 6. Figure 5-4 displays the template in an editor with the new code highlighted.

  9. Save the content-single.php file in your editor, and upload it to your web server.

    Be sure that you upload the content-single.php file, with the new changes, to the same location where you downloaded it from your web server: /wp-content/themes/twentynineteen/template-parts/content/.

  10. Refresh your post on your site to see your Custom Field data displayed.

    The data should look like the My Current Mood is: Happy message shown in Figure 5-3 earlier in this chapter.

Screenshot displaying the content-single.php file with the new Custom Fields code in a code editor.

FIGURE 5-4: The content-single.php file with the new Custom Fields code in a code editor.

WordPress now displays your current mood at the beginning of the posts to which you've added the mood Custom Field.

The entire code, put together, should look like this in your template:

<p>
My Current Mood is:
<?php
$key="mood";
echo get_post_meta( $post->ID, $key, true );
?>
</p>

Warning The code is case-sensitive, which means that the words you enter for the key in your Custom Field need to match the case of the $key in the code. If you enter mood in the Key field, for example, the code needs to be lowercase as well: $key="mood". If you attempt to change the case to $key="Mood", the code won't work.

You have to add this code for the mood Custom Field only one time. After you add the template function code to your template for the mood Custom Field, you can define your current mood in every post you publish to your site by using the Custom Fields interface.

Remember This example is just one type of Custom Field that you can add to your posts.

Getting WordPress to check for your Custom Field

The previous sections show you how to add the necessary code to your template file to display your Custom Field. But what if you want to publish a post in which you don't want the mood Custom Field to appear? If you leave your template file as you set it up by following the steps in the preceding sections, even if you don’t add the mood Custom Field, your post will still display My Current Mood is: without a mood because you didn't define one.

You can easily make WordPress check first to see whether the Custom Field is added. If it finds the Custom Field, WordPress displays your mood; if it doesn’t find the Custom Field, WordPress doesn’t display the Custom Field.

If you followed along in the preceding sections, the code in your template currently looks like this:

<p>
My Current Mood is:
<?php
$key="mood";
echo get_post_meta( $post->ID, $key, true );
?>
</p>

To make WordPress check whether the mood Custom Field exists, add this code to the line above your existing code:

<?php if ( get_post_meta( $post->ID, 'mood', true ) ) : {

Then add this line of code to the line below your existing code:

}
endif;
?>

Put together, the lines of code in your template look like this:

<?php
if ( get_post_meta( $post->ID, 'mood', true ) ) :
echo '<p>My Current Mood is: ';
$key="mood";
echo get_post_meta( $post->ID, $key, true );
echo '</p>
';
endif;
?>

The first line is an IF statement that asks, “Does the mood key exist for this post?” If it does, the value gets displayed. If it doesn't, WordPress skips the code, ignoring it so that nothing gets displayed for the mood Custom Field. The final line of code simply puts an end to the IF question. See the nearby “IF, ELSE” sidebar to find out about some everyday situations that explain the IF question. Apply this statement to the code you just added to your template, and you get this: IF the mood Custom Field exists, WordPress will display it, or ELSE it won't.

Remember You can find extensive information on working with WordPress template files within your theme in Book 6.

Exploring Different Uses for Custom Fields

In this chapter, I use the example of adding your current mood to your site posts by using Custom Fields. But you can use Custom Fields to define all sorts of data on your posts and pages; you’re limited only by your imagination when it comes to what kind of data you want to include.

Obviously, I can’t cover every possible use for Custom Fields, but I can give you some ideas that you may want to try on your own site. At the very least, you can implement some of these ideas to get yourself into the flow of using Custom Fields, and they may spark your imagination on what types of data you want to include on your site:

  • Music: Display the music you’re currently listening to. Use the same method I describe in this chapter for your current mood, except create a Custom Field named music. Use the same code template, but define the key as $key="music"; and alter the wording from My Current Mood is to I am Currently Listening to.
  • Books: Display what you're currently reading by creating a Custom Field named book, defining the key in the code as $key="book";, and then altering the wording from My Current Mood is to I Am Currently Reading.
  • Weather: Let your readers know what the weather is like in your little corner of the world by adding your current weather conditions to your published blog posts. Create a Custom Field named weather, and use the same code for the template. Just define the key as $key="weather"; and alter the wording from My Current Mood is to Current Weather Conditions.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.182.179