I currently have this,

$meta = get_post_meta(get_the_ID(), 'rw_agentPhone', true);
echo "office:";
echo $meta; // if you want to show

Which is fine provided there is a value for rw_agentPhone, but if the profile has no value entered it still displays office:, how can I rewrite this so that office: only dispalys if there is a value for rw_agentPhone.

I know this is basic php but I just haven't been able to crack this.


This is very basic. Invest some time in a PHP tutorial. It’s fun! :)

Anyway …

$meta = get_post_meta( get_the_ID(), 'rw_agentPhone', TRUE );
// get_post_meta() returns an empty string if it doesn’t find anything.
// We just test for this. If the string is not empty, we print it out.
'' != $meta and print "office: $meta";
  • Thanks, that was perfect, much simpler than what I was attempting. I had tried looking at some tutorials but I was thinking the solution would be an if/else but the solutions didn't seem appropriate, so I assumed I was going in the wrong direction.
    – Chuck
    May 24 '11 at 1:53
  • @Chuck You could use if ( '' != $meta ) { print '...'; } but the one-liner is so much more readable.
    – fuxia
    May 24 '11 at 1:56

If you prefer a regular if structure:

if ($meta = get_post_meta(get_the_ID(), 'rw_agentPhone', TRUE))
    echo 'office: ', $meta;
  • Thanks, I actually really like the simplicity of toscho's first answer, I am just getting started with wordpress/php though so to see the various ways to go about is helpful.
    – Chuck
    May 24 '11 at 23:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.