WordPress: how to display multiple values of a custom field key

In one of my recent adventures with WordPress I came across the need of having one or more custom fields values listed in one page. In my case, I wanted to list press quotes from theatre performances.

This is quite simple and useful, so I decided to write a quick post that may be useful to someone else.

Assumptions

I’m assuming you’re familiar with WordPress, so I’ll just skip the part where I’m supposed to explain how great custom fields are and how they add so much value and power to WP. It’s all true, but this is a “quick post”.

My requirements

As I mentioned, I needed to list quotes from the press for a specific theatre perfomance. Some performances had no quotes at all, while others had several. I also didn’t want to see the “Press Quotes” title, unless there were quotes. So my short list of requirements was something like this:

  1. Check if there are any custom fields in the post.
  2. If not, show nothing.
  3. If there are, echo the list of values, but not inside <li> tags (which is the default behavior if you use get_post_meta()). I want my values to be listed inside a <blockquote> and a <p>, to be semantically correct.

The code

I’ll assume we’re working within The Loop here, so wherever you’re adding this code to, it should be contained within something that may look like this:

<?php if(have_posts()) : while(have_posts()) : the_post(); ?>

<!-- This is just a comment, your code should come here -->

<?php endif; ?>

Inside the Loop, add this bit of code:

<?php
$press_quotes = get_post_meta($post->ID, "pressquote", false);
if ($press_quotes[0]=="") { ?>

<!-- If there are no custom fields, show nothing -->

<?php } else { ?>
					
<div class="pressQuotes">
	<h3>From the Press</h3>
								
	<?php foreach($press_quotes as $press_quotes) {
	echo '<blockquote><p>'.$press_quotes.'</p></blockquote>';
	} ?>
								
</div>
						
<?php } ?>

This is all you need to know:

  • $press_quotes: This is the variable that will store the value of each custom field. Replace by whatever suits you best (that’ll be 5 times in this code).
  • $press_quotes = get_post_meta($post->ID, "pressquote", false): pressquote is the actual Key of my custom field, as you can see in the image bellow:

custom-fields

If there are no custom fields, the code will echo a handful of nothing (or my little comment).

If there are, I’m showing the h3 tag with my pretty tittle, everything within a convenient div, for placement.

Then, I have to say what I want to repeat for each value (for each quote, in my case). So I write exactly that after the “echo” bit:

'<blockquote><p>'.$press_quotes.'</p></blockquote>'

Make sure to add the repeated HTML code within ‘ ‘ and the variable within . .

It’s as simple as that!

It may not be the only (nor the better) way of doing it, but it’s easy enough and it works. Let me know if you have any other methods!

References