WordPress.org

Ready to get started?Download WordPress

Forums

How to Display Multiple Custom Fields with Single Values (3 posts)

  1. hilmon
    Member
    Posted 3 years ago #

    Hi,

    I'm trying to find the best way of displaying the single values of lots of 10 custom fields... its a catalogue site.

    I'm thinking that there must be a better way than using get_post_meta() 10 times?

    $code = get_post_meta($post_id, 'code', true);
    $circa = get_post_meta($post_id, 'circa', true);
    $date = get_post_meta($post_id, 'date', true);
    $labels = get_post_meta($post_id, 'labels', true);

    etc etc...

    Database queries are not my strong point but I presume using get_post_meta() 10 times for say 10 post in a loop will make 100 queries rather than just 10... 1 for each post.... Or am I totally wrong about that?

    All the other similar functions to get meta keys and values don't seem to do this except maybe get post custom() which is really for multiple keys with multiple values.

    Layout wise I want to do different things with each value so I don't just want them spat out in a list.

    This is my first forum post and any help would be very much appreciated.

    :-p

  2. stvwlf
    Member
    Posted 3 years ago #

    When you use get_post_custom it returns an array that you can process and extract individual custom field keys-values from. Then you are doing one query per post rather than 10 as you said. You can use a PHP foreach loop to break the array into individual key-value pairs which you can assign to individual variables for further processing.

  3. hilmon
    Member
    Posted 3 years ago #

    Thanks for that.

    I'm sure this code could still be refined, but it does what I needed it to do...

    $my_names = array("code","circa","date", "label");
    $my_vars = array('$code','$circa','$date','$label');
    
    $custom_fields = get_post_custom($post_id);
    $i=0;
    while($i<=4){
      $my_custom_field = $custom_fields[$my_names[$i]];
      foreach ( $my_custom_field as $key => $value )
        $my_vars[$i] = $value ;
        echo $my_names[$i]." is ".$my_vars[$i]. "<br />";
        $i++;
    }

    Any suggestions on how I might refine this are very welcome!

    :-p

Topic Closed

This topic has been closed to new replies.

About this Topic