WordPress Custom Fields Tutorial, Part 2

This is a follow up to my previous post “WordPress Custom Fields Tutorial.” If you haven’t read that post, I recommend you do before reading this post.

In the last custom fields tutorial, I showed you how to add your favorite book to a custom field, and output that on a page of your site. What if you have more than one favorite book?

The Hard, Inflexible Way

Screen Shot 2013-06-11 at 4.29.06 PM

Based on the previous tutorial, you might create an entry for each book, and sequentially number them, as shown above, and then pull the data into your page one by one, in a way similar to below:

<div class="favorite-books">
	<h4>Favorite Books</h4>
	<ul>
		<li><?php echo esc_html(get_post_meta(get_the_ID(),'book1',true)); ?></li>
		<li><?php echo esc_html(get_post_meta(get_the_ID(),'book2',true)); ?></li>
		<li><?php echo esc_html(get_post_meta(get_the_ID(),'book3',true)); ?></li>
	</ul>
</div>

This is not very flexible and makes your life hard! Doing it this way, you would only be able to have 3 favorite books, without editing your theme to add support for more. Imagine how long this could take if you had 20 favorite books. Luckily, there is a better way!

The Flexible Solution

The most flexible solution would be to give all the custom fields the same name, so instead of ‘book1’, ‘book2’, ‘book3’, etc, you would just name all of them ‘book’, as seen below.

Screen Shot 2013-06-11 at 4.28.52 PM

Then, you can retrieve the all the books at once by changing the third parameter of the ‘get_post_meta()’ function. As mentioned last time, this can either be true or false, and tells WordPress if you are looking for a single value or not.  True means you are looking for just one value. If you pass false however, that means you are NOT looking for a single value, and you will get an array of all the values the match the custom field name. Look below:

<div class="favorite-books">
	<h4>Favorite Books</h4>
	<ul>
		<?php
		$books = get_post_meta(get_the_ID(),'book',false);
		foreach ( $books as $book ) {
			echo "<li>" . esc_html($book) . "</li>";
		}
		?>
	</ul>
</div>

Setting the code up this way, allows you to add a new favorite book whenever you want, without having to change your theme files. Just add another custom field, call it ‘book’, and another book will show up on your list.