0

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

2 Answers 2

3

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';
}
1
  • 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!!! Commented May 11, 2011 at 2:14
1

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.

5
  • thanks for the alternative I did end up using chips and just squashed it down to one line Commented May 11, 2011 at 5:00
  • 1
    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 { } Commented May 11, 2011 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. Commented May 11, 2011 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. Commented May 11, 2011 at 12:36
  • @Geert - how would your improvement fit this <?php $custom_field = (string) get_post_meta( $post->ID, "XYZ", true ); echo str_replace(' ', '', $custom_field); ?> Commented Jan 2, 2017 at 15:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.