Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Reusable Custom Meta Boxes Part 4: Using the Data

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

In Part 1, Part 2 and Part 3 of our custom meta box template tutorial series, we learned how to make a reusable meta box that gets all of the field information from an easy to read, easy to duplicate array. A lot of the data is simple to use by just echoing the meta field in your template or through a function, but some of the fields are more complex and require a bit more finesse to use properly. This tutorial will give you a basic idea of how to use this data and can be expounded on in countless ways.


Getting the Data

WordPress provides multiple ways to get post meta data.

Output All of the Data at Once

The simplest way to display the data is with the_meta() function. You can drop this right into your single.php template, but it won't give you the results you're probably after. It is a very literal output of the data in an unordered list prefixed with the key of each field as shown in the picture.

the_meta

Get a Single Field

The most common way to get data saved in a post meta field is with the get_post_meta() function. This is a simple way to target a specific field and store it in a variable that can be used later.

$custom_text = get_post_meta($post->ID, 'custom_text', true);

Using this code within the single post loop would put the text "Some text in a basic text input" into the variable $custom_text which could then be echoed or filtered, or whatever you would want to do with the string. When you're just dealing with a couple of fields, this is probably the way to go, but in our example, we are working with 11 different fields. Calling them all individually with this function would bloat your code unnecessarily since there's a way to get all the data at once.

Get All of the Data at Once

My favorite method when I'm working with this many fields is to use the get_post_custom() function. With this function, we can store all of the custom post meta fields in one array and then retrieve the data we want with the array key.

$post_meta_data = get_post_custom($post->ID); will give us an array that looks like this:

Array
(
    [custom_text] => Array (
            [0] => Some text in a basic text input
        )
    [custom_textarea] => Array (
            [0] => A paragraph or two from a textarea. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique quam mi. Sed eget ligula sit amet ante dapibus tristique. 

Mauris vel enim mauris, vitae mattis tortor. Praesent at adipiscing massa. Fusce quis eros vel sem pharetra consequat imperdiet ut est.
        )
    [custom_checkbox] => Array (
            [0] => on
        )
    [custom_select] => Array (
            [0] => one
        )
    [custom_radio] => Array (
            [0] => two
        )
    [custom_checkbox_group] => Array (
            [0] => a:2:{i:0;s:3:"one";i:1;s:5:"three";}
        )
    [custom_post_id] => Array (
            [0] => 109
        )
    [custom_date] => Array (
            [0] => 05/25/2012
        )
    [custom_slider] => Array (
            [0] => 15
        )
    [custom_image] => Array (
            [0] => 413
        )
    [custom_repeatable] => Array (
            [0] => a:3:{i:0;s:22:"text from a repeatable";i:1;s:27:"more text from a repeatable";i:2;s:33:"repeatable text fields are great!";}
        )
)

As you can see from this array, WordPress stores each field as an array because it is possible to have more than one value for the same field. You'll probably also notice that a few of the fields are serialized. Let's dig more into handling the data from each field and cover how to fix that.


Simple Input Fields

The text and textarea fields are pretty simple to deal with. You can echo them with one of the following examples:

echo $post_meta_data['custom_text'][0];

echo apply_filters('the_content', $post_meta_data['custom_textarea'][0]);

$custom_checkox = $post_meta_data['custom_checkbox'][0];

if ($custom_checkbox == 'on') {
	do_stuff();
}

The first line will simply output the string as-is, and the second line will convert the line breaks to paragraphs with WordPress' the_content filter. You can use these same methods for select, radio, date, and slider fields as well.

The last line shows how you can test to see if a checkbox has been selected or not. If it is, you can perform various functions, or any number of things.


Serialized Data

Our check box group fields and repeatable fields are storing arrays which get serialized in the database. Before we can output this data, we have to unserialize it.

$custom_checkbox_group = unserialize($post_meta_data['custom_checkbox_group'][0]);

$custom_repeatable = unserialize($post_meta_data['custom_repeatable'][0]);

The unserialize() function is a basic PHP function that converts our data into an array that is easier to use. The code above will give me two arrays that look like this:

Array
(
    [0] => one
    [1] => three
)
Array
(
    [0] => text from a repeatable
    [1] => more text from a repeatable
    [2] => repeatable text fields are great!
)

Now I can loop through the arrays however I want to use them in my output. It's important to note that in the repeatable field, if you also make it sortable as our example in Part 3 of our custom meta box template tutorial does, the keys in the array will automatically store in the order of 0, 1, 2, 3, etc. and not in the order in which they were originally entered before sorting them.

echo '<ul class="custom_repeatable">';
foreach ($custom_repeatable as $string) {
	echo '<li>'.$string.'</li>';
}
echo '</ul>';

This example will output an unordered list of each string saved in the $custom_repeatable array.


Specialized Data

For our Post List and Image fields, we saved an ID. There may be some very rare cases in which you want to output just the ID, but most likely you'll want to use the ID to get more information.

$custom_post_id = $post_meta_data['custom_post_id'][0];
echo '<a href="'.get_permalink($custom_post_id).'">'.get_the_title($custom_post_id).'</a>';

$custom_image = $post_meta_data['custom_image'][0];
echo wp_get_attachment_image($custom_image, 'thumbnail');

Conclusion

This tutorial shows the most basic ways that you can use the data that we've stored with our reusable custom meta boxes. Being able to save extra data and use it in themes and plugins opens up a whole new world of possibilities with WordPress. What will you use it for?

Advertisement