WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Ok so i am trying to use WordPress's custom fields and have them working but now i have some php code i need help with.

<a href="<?php echo get_post_meta( $post->ID, '_ct_text_4dc9e9f74d000', true ); ?>">Go To Store!</a>

The above code is what i have for right now. Is there a way to setup a if and else statement so if there is a value in the custom field then show that but else show N/A if there is no value present

share|improve this question
up vote 2 down vote accepted

You mean something like this?

$customhref = get_post_meta( $post->ID, '_ct_text_4dc9e9f74d000', true );

if ( $customhref ) {
     <a href="<?php echo $customhref; ?>">Go To Store!</a>
} else {
     echo 'N/A';
share|improve this answer
Thanks that worked perfectly. I have been widening my skills in web development and php is still in the ok need to still learn and research. I was trying to do it way differently. Thanks!!! – xLRDxREVENGEx May 11 '11 at 2:14

Chip's answer is great (and earned a +1), but just as an alternative as you are learning PHP, I prefer this style as it takes only a single line in the file that I will use and integrates better with the flow of the HTML.

<?php if(get_post_meta( $post->ID, '_ct_text_4dc9e9f74d000', true )) : ?><a href="<?php echo get_post_meta( $post->ID, '_ct_text_4dc9e9f74d000', true ); ?>">Go To Store!</a><?php else : ?>N/A<?php endif; ?>

Again, this is just a matter of preference and it might be helpful for you to see other ways to do the same thing.

share|improve this answer
thanks for the alternative I did end up using chips and just squashed it down to one line – xLRDxREVENGEx May 11 '11 at 5:00
you're calling get_post_meta twice. You could assign the result in the first if to shorten and optimize code a bit: if ($x = get_post_meta($post->ID, 'field', TRUE)) { echo $x; } else { } – Geert May 11 '11 at 5:34
@Geert...well played! Bad form on my part. I was trying too hard to demonstrate the one line approach and forgot the common sense of not running that function twice. – tollmanz May 11 '11 at 5:40
I'm not a big fan of forcing code onto one line. PHP doesn't care about whitespace, and I like to make my code human-readable - mainly, so that later on, I can follow/remember what code I wrote, and why. :) Mainly a matter of personal preference, I'm sure. – Chip Bennett May 11 '11 at 12:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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