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

25 March 2009, in WordPress | 42 comments »

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

There are 42 comments:

  1. WordPress seems to be an exciting resource for fast website development.

    I didn’t had the time to dive into the doc’s but from what I can see from my own blog, I’m sure that I will have lots of things to mess around with it.

    For me it’s to soon to state that WordPress is or not suitable for more complex site requirements, but for sure, a simple a slick backoffice operated website, WordPress will surpass other CMS’s on the market, just as long is kept simple for the developers.

    BTW: Olá Lili :D

  2. Ey your blog is very good, the design and the information. i will back here for more.

    About this post i am experimenting too with custom fields so ill give it a try

  3. Andrew Fox says:

    Hello.

    I would highly recommend plugins like Custom Field Template or (even better) More Fields. These help make the custom fields feel a lot more part of the admin interface and less techy. They also come with automatic field types. This is great for client sites.

    Keep up the good work!

  4. Great post, but one correction- this code doesn’t necessarily need to be used within the loop.

    The only time this *needs* to be within the loop is if the custom field values are being pulled from a post, and then only because this code needs $post->ID to be defined.

    If you’re using this code to display custom field values of static pages, or if you’re getting the post ID through some method other than “$post->ID”, you can use this wherever you like.

    • Paul says:

      hi
      you say “if you’re getting the post ID through some method other than “$post->ID”, you can use this wherever you like.”
      What other ways can you get a post ID? – i want to be able to link two posts together and share custom fields between them if possible.
      cheers

  5. musam says:

    thank you so much! really great trick!
    yeah! :D

  6. Kathy says:

    I tried using this and I get an error message with foreach:

    Warning: Invalid argument supplied for foreach()

    this is the code i’m using

    ID, ‘affiliates’, false); ?>

    <?php foreach($affiliatesfields as $ads) {
    echo '’.$ads.”;
    } ?>

  7. Toure says:

    Hi, I am looking for a way to display many images based on custom fields.
    I am working on a type of Image gallery where a post will have multiple images and I just don’t wanna have to insert them withing the post directly.
    Any help will be appreciated.
    By the way, I am modifying the theme “No-frills 2.1.7 by Jess Kim”

  8. inayaili says:

    @Kathy: try using

    foreach($affiliatesfields as $affiliatesfields)

    instead of what you’ve got.

  9. Luke says:

    Anyone know of a way to then sort the custom fields in order to display them in a controlled order? They seem to display at random, how are they currently sorted using this method?

  10. I’m often looking for brandnew articles in the WWW about this theme. Thx.

  11. Tadd Mencer says:

    This was perfect! It was exactly what I needed to get thing rolling. Of course I had to change it because I was using it to pull images for an auto scrolling feature on a client site .. BUT .. it pointed me in the right direction. THANK you!

  12. Allen says:

    Very good explanation! It was definitely something I was looking for to display a rotating testimonial plugin for a client’s sidebar.

  13. Awesome, I didn’t heard about this topic till now. Thx!!

  14. Действительно вы очень интересно пишите, не зря мне друзья посоветовали, спасибо за посты!

  15. Leah Raeder says:

    Thanks so much for this! Works perfectly for the similar pull-quote effect I needed.

    Lovely blog and work, as well. I’ll certainly be subscribing. Cheers.

  16. Niranjan says:

    I AM VERY HAPPY BECAUSE I GOT HELP FROM THIS FOR GIVING CUSTOM VALUES

  17. Pete says:

    I used this for entering Paypal “Pay Now” buttons! Works awesome and is way easier than entering it into the “HTML” or “Visual” mode in the WordPress backend.

    THANKS!

  18. Jason says:

    I have been going slightly crazy trying to deal with the issue. I have tried a few different idea’s, but this one is a winner for my needs.

    I am using it in almost the exact way described, so i don’t need too much modification.

    Thanks.

  19. Worked perfect. Thank you!! BTW, the “Assumptions” are awesome. Skip to the point writing makes for a good, easy to read, post. Thanks again.

  20. colin says:

    hi!

    great tutorial, i have a Q:

    how can i modify this so it only shows two of the items in pressquote (even if there were actually say five) ?

    like.. how can i make it loop twice only instead of doing it ‘foreach’ .. ?

    thanks!

  21. colin says:

    OK here’s how to limit the number of times it produces something from the custom field list ( array )..

    using the code form above, swap this in there:

    From the Press

    <?php
    $i = 0;

    foreach($myImage as $newImage) {

    while($i < 2){
    echo '';
    echo '';
    $i++;
    }} ?>

    :)

  22. colin says:

    sorry for all the comments – please delete the useless stuff. no idea why the code isn’t showing up…

    <?php
    $i = 0;

    foreach($myImage as $newImage) {

    while($i < 2){
    echo '’;
    echo ”;
    $i++;
    }} ?>

  23. Toure says:

    I guess the code might be different if has to be in a single page’s post.
    I tried it but it’s giving duplicate image of the first custom field.
    Any Idea how it should be done in a single page’s post?
    Thanks for any help.

  24. Attila says:

    Hi,

    Great idea, but what if every “pressquote” has other “attachements” like link, title and rating? (I mean like: pressquote1 has link1, title1 and rating1, pressquote2 has link2, title2 and rating2, and so on.. and I want all to be displayed.) How to manage this?

    The specific example: I have a site with book-reviews. I want to attach to every review an excerpt of others’ reviews: a title with link, reviewer’s site, excerpt and rating, and display them beneath my review. There will be reviews with no other attachable reviews, and there will be many other reviews to attach. Can I handle this with custom fields?

  25. Awesome! Thanks for sharing this great post……..

  26. Rob Kanner says:

    Correct me if I’m wrong, but Dark Hat SEO approaches don’t function anyway, appropriate?

  27. DancingKim says:

    Greetings, i’m a professional dancer. i’d like to make a showreel with regard to my promotions. I also prefer to use some animation. Can someone suggest me a great animation studio, but not really very expensive? I’m here for 3 months for a tour.
    Love
    Kim.

  28. This post helped a lot for solving my array based custom field issues. Thanks a lot. :)

  29. Katy says:

    This is really helpful, thank you. I am trying to display images as my custom field, the value of my field ‘thumb’ is the URL of the image. I would be tremendously grateful if someone could tell me what to put instead of

    echo ‘

    ‘.$thumbnails.’

    ‘;

    In order to get the images to show up.

    Thank you thank you thank you!!

  30. Katy says:

    the html in my comment above got stripped out – it was meant to say (I have replaced

  31. Scott says:

    I know this is an older post. I am trying to find a way to display 1 of 3 things, Nothing, or text 1, or text 2. Text 1 and 2 must be able to be styled differently. (red background for one, green for the other)Is this possible?

  32. Stephen says:

    I hope someone can help me. Is there anyway to modify this so that instead of showing every one of the pressquote custom fields, it picks and displays one at random?

    So if there were 3 pressquotes instead of listing all 3 it would randomly pick 1?

    I want to use this to display a random video

    Thanks

  33. Nafees Ahmed says:

    Thanks for your help. I used your code to display multiple images of a custom field key. It is really work.

  34. Broeiend says:

    Thnx for this post, helped out a lot!

    I modified your code a bit. With this code you can display a random value of the custom field.

    I used it to display a random youtube video by id:

    if( get_post_meta( $post->ID, “video”, true ) ) :
    $custom_fields_video = get_post_meta($post->ID, “video”, false);
    if ($custom_fields_video[0]==””) {
    // do nothing
    } else {
    $videos = array();
    foreach($custom_fields_video as $video) {
    $videos[] = $video;
    }
    }
    $rand_video = array_rand($videos);
    $videos[$rand_video];
    endif;

  35. Sayed Arif says:

    THANX

Leave a comment: