WordPress.org

Ready to get started?Download WordPress

Forums

Need help with PHP for get_post_meta (3 posts)

  1. Eric Amundson
    Volunteer Moderator
    Posted 5 years ago #

    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

  2. sbonsell
    Member
    Posted 5 years ago #

    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; ?>
  3. Eric Amundson
    Volunteer Moderator
    Posted 5 years ago #

    Perfect, Sean, that did it.

    I was so close, but fudging the syntax.

    Thank you!

Topic Closed

This topic has been closed to new replies.

About this Topic