Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

2 Answers

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>
<?php
} 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
add comment

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
add comment

Your Answer

 
discard

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.