Advertisement
  1. Code
  2. WordPress

Mastering WordPress Meta Data: Working With Loops

Scroll to top

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.

Using Foreach Loops on Arrays

The standard WordPress loop is a while loop, as in "while there are items to loop, continue the loop." Often times, when working with meta data, it's easier to work with a foreach loop.

These loops allow us to write our PHP as if we were working with a single array, and then, for each item, output each item from a multi-dimensional array through the same loop.
Earlier we looked at this array:

1
2
$heroes => array(
3
		'Luke'        => array(
4
		'full_name'   => 'Luke Skywalker',
5
		'home_planet' => 'Tatooine',
6
		'trope'       => 'Unlikely Hero',
7
	),
8
		'Leia'        => array(
9
		'full-name'   => 'Leia Organa',
10
		'home_planet' => 'Alderaan',
11
		'trope'       => 'Badass Princess',
12
	),
13
		'Han'         => array(
14
		'full_name'   => 'Han Solo',
15
		'home_planet' => 'Corell',
16
		'trope'       => 'Lovable Rouge',
17
	),
18
);

If we wanted to make this array readable, with proper markup we would create a foreach loop.

We usually setup foreach loops with plural and singular forms of the variable, i.e., foreach ( $heroes as $hero ) and from there we can use the singular variable to represent each item in the array.

We can then treat our multi-dimensional array as one single array.

1
2
$heroes => array(
3
		'Luke' 	=> array(
4
			'full_name' 	=> 'Luke Skywalker',
5
			'home_planet' 	=> 'Tatooine',
6
			'trope' 		=> 'Unlikely Hero',
7
	),
8
		'Leia' 	=> array(
9
			'full-name' 	=> 'Leia Organa',
10
			'home_planet' 	=> 'Alderaan',
11
			'trope' 	=> 'Badass Princess',
12
	),
13
		'Han' 	=> array (
14
			'full_name' 	=> 'Han Solo',
15
			'home_planet' 	=> 'Corell',
16
			'trope' 		=> 'Lovable Rouge',
17
	),
18
);
19
20
echo '<ul>';
21
22
foreach ($heroes as $hero) {
23
        echo '<li>Full Name: '.$hero['full_name'].'</li>';
24
} //end of the foreach loop

25
26
echo '</ul>';

This is an abstract example, but I'm sure you can see the power. Instead of rewriting (and having to update) the same markup three times you just write it once, and let PHP loop through it three times.

These six simple lines of code could just as easily handle fifty posts as five showing us the power of foreach loops to write easy to manage, scalable code.

In this next example, we take an array of post ids, and foreach post return the name of a field youtube_name as a link that is set in the youtube_link field. These six simple lines of code could just as easily handle fifty posts as five showing us the power of foreach loops to write easy to manage, scalable code.

1
2
$posts = array( 5, 8, 13, 21, 34 );
3
foreach ( $posts as $post ) {
4
	$link = get_post_meta( $post, 'youtube_link', 'single' );
5
	$name = get_post_meta( $post, 'youtube_name', 'single' );
6
	echo '<a href="'.$link.'">'.$name.'</a>';
7
} // end foreach loop

Using get_post_meta() in the Main WordPress Loop

So far I've been manually specifying post IDs, but when used in the main WordPress loop we can set the ID in get_post_meta() manually with get_the_ID(). So using the same custom fields as we used in the last example, but showing them as part of the main loop, if we wanted to add the youtube video below the post content, we could simple add, after, the_content(); something like this:

1
2
$link = get_post_meta( get_the_ID(), 'youtube_link', 'single' );
3
$name = get_post_meta( get_the_ID(), 'youttube_name', 'single' );
4
echo '<a href="' . $link . '">' . $name . '</a>';

Combining a while and foreach Loop

Often times we will have one custom field that contains an array of serialized data for related information. For example, one field may contain a video's title, mime type, URL and description.

Serialized storage is especially useful when multiple items can be added to a field. Working with these times of fields can be tricky in the main WordPress loops. The easiest way to handle them is with a secondary loop inside of your main loop.

In this example, I have added to a standard WordPress post loop, which is a while loop, a second loop, that loops through each video field to construct an HTML5 video players, one foreach video.

It doesn't matter if there is one video or ten. These few simple lines of code will create a player for each one.

1
2
if ( have_posts() {
3
	while ( have_posts() )  {
4
		the_post();
5
		the_content();
6
		$videos = get_post_meta( get_the_ID(), 'videos', false );
7
		foreach ( $videos as $video ) { ?>
8
            <div class="video">
9
                <h3 class="video-title"></h3>
10
                <video width="320" height="240" controls="controls"><source src="<?php echo $video['url']>" type="<?php echo $video['mime_type']; ?>" />
11
                    Sorry your browser does not support HTML5 video.
12
                </video>
13
                <?php echo $video['description'] ?>
14
            </div>
15
        <?php
16
        } //endforeach

17
    } //endwhile

18
} //endif

Almost There

Through this series, so far, we've covered what meta data is in WordPress and applied this knowledge to learn about PHP arrays and loops. We've also looked at some practical examples about how to use this data, or arrays of data in the loop.

This is the first step to learning to use WordPress as a content management system. The next step is to learn how to query the database by meta fields, which is what we will cover next time.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.