15. Custom Fields

Before the existence of custom post types, custom fields were the tool of choice to enhance out-of-the-box WordPress functionality. I once built a 23,000-page directory using WordPress and custom fields. They give you precise control over metadata for specific posts and pages.

Now that we have custom post types and greater control over data tied to posts and pages, custom fields are used primarily for specific functions, such as toggling elements on posts or pages, showing or hiding content, and so on. In our theme we’ll be using custom fields to set the URL of our home page slider.

What you’re about to learn

• How to set custom fields in a post

• How to display all custom fields on a post

• How to use custom field data for a specific purpose

Setting Custom Fields

Custom fields are handled by key/value pairs. When a user admin defines a new custom field, he names the new metadata with a key and then sets the value to be associated with it. A simple example could be storing colors. The key would be called “colors” and the value would be “blue.” One key can be used multiple times on a single post. So you can set blue, red, and yellow to the “colors” key. When you call the key to display, WordPress returns an array of values associated with the specific key. We’ll get into that later. For more info on custom fields, go to http://wdgwp.com/Custom_Fields.

To set a custom field, go to the bottom of the Edit Post page and locate the Custom Fields section (Figure 15.1). If you don’t see the Custom Fields section, go to Screen Options at the top of the page and toggle Custom Fields “on” (Figure 15.2).

Image

Figure 15.1. Custom Fields section of the Edit Post page.

Image

Figure 15.2. Screen Options toggle for Custom Fields.

Here you’ll see two fields. The left field is labeled “name.” Here you’ll put the name of the custom field (that is, the key). The right field is the value. For now, enter “blue” (Figure 15.3). Once your fields are set, click Add Custom Field. This sets your custom field key and value pair. It’s always good to click Update or Save at the top of the post to make sure everything saves accurately.

Image

Figure 15.3. Adding the first custom field.

Now that you’ve created your first custom value, you’ll see a different layout in the Custom Field section. Figure 15.4 shows a drop-down menu from which you can choose existing keys. If you want to add a new custom field, you can click the Add New text below the drop-down. You’ll also notice that your custom field has been saved and now appears above the Add New section.

Image

Figure 15.4. Adding additional custom fields.

This was a very basic example to show you how to save data in the Custom Fields section. Remember that these key/value pairs are specific to each post; none of this data is global. Also, it’s important to note that this data is saved as a string, so if you want to, you can save HTML markup in the values field as well. If you’re building your theme for a specific person or company, you can create these custom values on behalf of the User Admin. Otherwise, it’s important to create documentation on how to implement custom values and how they’ll be used in the theme.

Displaying Custom Fields

As with other aspects of WordPress, there are several ways to accomplish a single task. With custom fields, you can display a list of all the values saved to a single post. You can also request specific values by passing keys as a parameter. Let’s start by displaying a list of all of our favorite colors using the the_meta() function. You can visit the codex for more info on the the_meta() function at http://wdgwp.com/the_meta.

Let’s assume I’ve added blue, red, and yellow as values under my “colors” key. When I add the following WordPress Template Tag:

<?php the_meta(); ?>

to my loop it, outputs an HTML list of all my custom fields keys and their values.

<ul class='post-meta'>
  <li><span class='post-meta-key'>colors:</span> blue, red, yellow</li>
</ul>

While this function makes it easy to display all my keys and their values, it really doesn’t provide a great deal of control over the data.

Controlling Custom Fields and Their Values

Let’s dig deeper into custom fields and create an example where we need to manipulate a specific custom value as a variable. Suppose the user admin has created a page where he is accepting donations to his favorite charity. Let’s say his goal is to reach $1,000 in donations. You can set the donations goal and current dollar figure as custom fields, then subtract the difference so users will know how much more is needed to reach the goal.

Start by setting 1000 as the value for the “goal” key. Then set 450 as the “current_figure” key. In this case the goal is to reach $1,000 and we’ve already accepted $450 in donations. Your post custom fields area should look like Figure 15.5.

Image

Figure 15.5. Custom fields donations.

With the custom fields set, we now need to store the data from the custom fields in variables, perform an equation on those variables, and display them. For the purposes of this example, we’re temporarily putting this code at the end of The Loop in the page.php template. We’ll remove it later as it’s just a teaching example and won’t be included in the new theme.

In order to manipulate specific values, we need to request them. The the_meta() function won’t work here. Instead, we’ll use the get_post_custom_values() function, which lets us pass a key as a parameter and get back an array of values. For more information on this function, go to http://wdgwp.com/get_post_custom_values. Since we’re “getting” the values, we need to save them to a variable. The following PHP code requests the two values we need and stores them in variables:

<?php
    $j2theme_donation_goal = get_post_custom_values( 'goal' );
    $j2theme_current_figure = get_post_custom_values( 'current_figure' );
?>

It’s important that the parameters are exactly the same as the key names set in the post. Once we have the data saved as variables we can manipulate them as we see fit. Remember that keys can hold multiple values, so we will always receive an array. If there’s only one value, we’ll get an array with a single index.

<?php
    $j2theme_donation_diff = $j2theme_donation_goal[0]
        - $j2theme_current_figure[0];
?>

The next line creates a new variable called $j2theme_donation_diff that equals $j2theme_donation_goal[0] minus $j2theme_current_figure[0]. We appended [0] to the end of the arrays to grab the first element in the array.

Now we can actually display the data. The next line echoes an <h1> tag, stating how far we are from our fundraising goal:

<?php
  echo '<h1>We are only $' . $j2theme_donation_diff . ' away from our $' .
       $j2theme_donation_goal[0] . ' goal. Donate Today!</h1>';
?>

In four lines of code we can create some pretty significant functionality. Now the user admin just needs to go to the Donate page and update the current_figure custom field, and the page will update with the new figures. The complete PHP code seen below should be added to the page.php in The Loop (again, just for this example):

<?php
    $j2theme_donation_goal = get_post_custom_values( 'goal' );
    $j2theme_current_figure = get_post_custom_values( 'current_figure' );
    $j2theme_donation_diff = $j2theme_donation_goal[0]
        - $j2theme_current_figure[0];
    echo '<h1>We are only $' . $j2theme_donation_diff . ' away from our $' .
        $j2theme_donation_goal[0] . ' goal. Donate Today!</h1>';
?>

This outputs the following HTML:

<h1>We are only $550 away from our $1000 goal. Donate Today!</h1>

If you wanted to have some real fun with this, you could create a gauge or other diagram and use jQuery and these two values to create a graphical representation of how far we are from the goal.

Home Page Slider URL

Our theme doesn’t require anything this complex. We’ll be using a custom field to house the URL for our home page slider. Before we continue, I challenge you to complete the next step without reading the rest of this chapter. The task is to add a custom field to the slider posts we’ve created to generate the home page slider. You’ll need to create a custom field with a key of “j2theme_url” and a value of “http://localhost/sample-page” (this URL is only temporary and should be modified for your site). Then display that URL in The Loop (you’ll learn how to use the URL below).

Give it a shot on your own. If you can’t get it, go ahead and finish this chapter. I’ll walk you through it now. Start by adding a new custom field in a post. The key will be “url” and the value will be “http://localhost/sample-page,” as seen in Figure 15.6.

Image

Figure 15.6. URL custom field.

For now we’ll put the following PHP code into the single.php file. This will be for testing only; in the next chapter, we’ll place it in The Loop for the slider (at that point you can remove it from single.php):

<?php
  $j2theme_slider_url = get_post_custom_values( 'j2theme_url' );
  echo $j2theme_slider_url[0];
?>

This should be pretty straightforward. We call the get_post_custom_values() function, pass it the parameter of “j2theme_url,” and store what it returns in the variable $j2theme_slider_url. Then we echo the first value in the array. This outputs the URL we saved in the custom field “http://localhost/sample-page.”

That’s it. Pretty simple, right?

What’s Next

In the next chapter we’ll tie what we learned in Chapter 14, “Featured Images,” in with custom values and WP_Query() to create our slider. WP_Query() is a powerful WordPress class that lets us manipulate and change The Loop. This gives us greater control over the exact posts that get displayed.

..................Content has been hidden....................

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