• On a site, I’m using get_posts_meta to check if there are data in either of two custom fields and, if so, echo them on the screen.

    What I originally put together was clunky and I’d like to improve it.

    Here’s what I have:

    <dl class="skills">
    <!-- Get Required -->
    <?php if(get_post_meta($post->ID, "Required", true)): ?>
    <dt>Required:</dt>
    <dd class="required"><?php $key="Required"; echo get_post_meta($post->ID, $key, true); ?></dd>
    <?php endif; ?>
    <!-- End Required -->
    <!-- Get Preferred -->
    <?php if(get_post_meta($post->ID, "Preferred", true)): ?>
    <dt>Preferred:</dt>
    <dd class="preferred"><?php $key="Preferred"; echo get_post_meta($post->ID, $key, true); ?></dd>
    <?php endif; ?>
    <!-- End Preferred -->
    </dl>

    This works great except when there are no custom fields with either key, in which case, an empty definition list displays.

    I’d to test to see if either the Required or Preferred keys exist and, if so, include the definition list.

    Problem I’m having is that I can’t nail down the correct PHP to accomplish this. I’d appreciate any help you can offer.

    Thanks in advance,
    Eric

Viewing 2 replies - 1 through 2 (of 2 total)
  • Eric,
    This is what I’m thinking would work. Just check if either keys exist, then start the definition list. There might be a more elegant solution though if anyone else wants to chime in.

    <?php if(get_post_meta($post->ID, "Required", true) || get_post_meta($post->ID, "Preferred", true)): ?>
    
    <dl class="skills">
    <!-- Get Required -->
    <?php if(get_post_meta($post->ID, "Required", true)): ?>
    <dt>Required:</dt>
    <dd class="required"><?php $key="Required"; echo get_post_meta($post->ID, $key, true); ?></dd>
    <?php endif; ?>
    <!-- End Required -->
    <!-- Get Preferred -->
    <?php if(get_post_meta($post->ID, "Preferred", true)): ?>
    <dt>Preferred:</dt>
    <dd class="preferred"><?php $key="Preferred"; echo get_post_meta($post->ID, $key, true); ?></dd>
    <?php endif; ?>
    <!-- End Preferred -->
    </dl>
    
    <?php endif; ?>
    Thread Starter Eric Amundson

    (@sewmyheadon)

    Perfect, Sean, that did it.

    I was so close, but fudging the syntax.

    Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Need help with PHP for get_post_meta’ is closed to new replies.