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!
I would write a function to handle the monotony of this task.
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: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
You could use get_post_custom()
It’s not a lot different, but a little less code.