WordPress: How to Display Multiple Custom Field Key Values

in Tutorials & Samples/Wordpress

I use WordPress’ custom fields often for many of my projects. In most cases, I only use a single unique key for the custom field. But on a recent project, I had to use the same custom field key multiple times on the same post. In my case, I had a post that stores multiple URL sources for a given article. Some articles may have 2 or more sources while others may not have any sources. All these sources were stored as a custom field called ‘source’ for any given article.


I was not sure if WordPress supported this since I had never done it before. But, after some investigation, I was able to do this very easily with minimal code in my template file. It turns out that the get_post_meta() method returns an array of all custom fields that match the value that you give it. So, all you need to do is loop through the returned array to display all custom fields that match the desired value. In my case, the custom field value was ‘source’

Here is the code below:

$sources = get_post_meta($post->ID, "source", false);
if (count($sources)) { ?>
	<?php foreach($sources as $source) {
	echo '<a href='.$source.' target="_blank">'.$source.'</a><br/>';
	} ?>
<?php } ?>

Keep in mind that the code above must be put inside The Loop.


Mifty Yusuf is a Montreal-based software developer who enjoys playing with new web technologies as well as comic books and illustrations. He beleives that, no matter what the question is, the answer is always Batman!

Leave a Reply

Your email address will not be published.


Latest from Tutorials & Samples

Go to Top