Cleaner way to access custom fields in code?

I have 15 custom fields that I use to generate reviews for my site. Currently I access each field like this:

//Buy or rent, type home, price
                 if ( get_post_meta(get_the_ID(), 'survey_home_type', true) ) {
                    echo get_post_meta(get_the_ID(), 'survey_home_type', true) . " - ";
                 } 
                 if ( get_post_meta(get_the_ID(), 'survey_buy_or_rent', true) ) {
                    echo get_post_meta(get_the_ID(), 'survey_buy_or_rent', true) . " for ";
                 }
                 if ( get_post_meta(get_the_ID(), 'survey_purchase_price', true) ) {
                    echo get_post_meta(get_the_ID(), 'survey_purchase_price', true);
                 } elseif ( get_post_meta(get_the_ID(), 'survey_rent', true) ) {
                    echo get_post_meta(get_the_ID(), 'survey_rent', true);
                 } 

Is there a better way to do this? I tried using get_post_custom but it seems to mainly deal with arrays, not single items. I could also declare all the variables ahead of time, such as $rent, $purchase_price. I would like to hear any advice!

Related posts

Leave a Reply

2 comments

  1. I would write a function to handle the monotony of this task.

    function my_print_meta($id, $key, $alternate = '')
    {
        if($value = get_post_meta($id, $key, true))
            echo $value;
        else
            echo $alternate;
    }
    

    Notice in the function that I only call get_post_meta once and store the value in a variable so that two separate database queries don’t need to be made. With this function set, I would then call it in a template file using:

    my_print_meta(get_the_ID(), 'survey_home_type', 'No Home Type');
    

    Now, realize that this function, with the way that it manages the “alternate” text might not work for your template, but this is just an idea to get you going

  2. You could use get_post_custom()

    It’s not a lot different, but a little less code.

    $meta = get_post_custom( $post->ID );
    if( $meta ) 
    { 
        echo $meta['survey_home_type'];
        echo $meta['survey_buy_or_rent'];
        echo $meta['survey_rent'];
    }