Advertisement
Theme Development

Reusable Custom Meta Boxes Part 4: Using the Data

by

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?

Related Posts
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    WordPress
    Mastering WordPress Meta Data: Querying Posts and Users by Meta DataMetadata
    So far in this series you've learned how to access WordPress meta data, and work with the arrays in which they are returned. We don't just add custom fields to WordPress posts so we can display this information, but it also so we can sort by it. Now that you know how to retrieve and display meta data, it's time to learn how to customize the WordPress loop to return only posts with specific meta values.Read More…
  • Code
    WordPress
    Mastering WordPress Meta Data: Working With LoopsMetadata
    In the first two parts of this series, we covered what meta data is in WordPress and how to work with the arrays that are typically returned. Now that you've learned to do the detective work necessary to find the structure of an array, it's time to learn to use loops to automate the process of outputting an array. Once you learn this important skill you will never have to write repetitive HTML markup again.Read More…
  • Code
    WordPress
    Mastering WordPress Meta Data: Understanding and Using ArraysMetadata
    In the first part of this series, we covered what WordPress meta data is, how it can be retrieved, and the various data types (such as objects or arrays) in which it can be returned. Now it's time to learn about the different types of arrays. When you write an array manually you know what its structure is an what the name of each index is. But when you are building arrays by querying a database, you are going to need to do some detective work to determine the structure of the data returned and the names of the indexes.Read More…
  • Code
    PHP
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…
  • Code
    Plugins
    Communicating With the WordPress.org Plugin APIWordpressdotorg plugin api border 400
    Over the last few weeks I have been wondering on how to possibly pull data about my plugins hosted on WordPress.org and display it on my website. The first thing that came to mind was "Web Scrapping" but quite frankly this is a lot of work, feels like going back in time, and is not something a good web citizen should do. In some cases, it could be illegal.Read More…