phpwordpressconditional-statements

Adding punctuation to a WP meta data


I have the below code, but am looking to add punctuation to the end of each item. Either a colon or a comma. Is there an easy way to do this in the below code, or is it better to do it as part of the code registering the meta box? I can supply that code if this is a better solution. I am concious that placing it in the above HTML means the punctuation will display even if the meta-data is empty (therefore not displaying).

Also, is there some code I can add to the above to make the calls conditional, so if they are empty they won't display at all? Currently I am left with empty li tags.

Thanks

<ul class="credits">
<li><?php echo get_post_meta($post->ID, "_role1", true); ?></li>
<li><a href="<?php echo get_post_meta($post->ID, "_url1", true, ','); ?>" target="_blank"><?php echo get_post_meta($post->ID, "_name1", true); ?></a></li>
<li><?php echo get_post_meta($post->ID, "_role2", true, ':'); ?></li>
<li><a href="<?php echo get_post_meta($post->ID, "_url2", true, ','); ?>" target="_blank"><?php echo get_post_meta($post->ID, "_name2", true); ?></a></li>
<li><?php echo get_post_meta($post->ID, "_role3", true, ':'); ?></li>
<li><a href="<?php echo get_post_meta($post->ID, "_url3", true); ?>" target="_blank"><?php echo get_post_meta($post->ID, "_name3", true); ?></a></li>
</ul>

Solution

  • Here's the code:

    <?php
    $role1 = get_post_meta($post->ID, "_role1", true);
    $url1 = get_post_meta($post->ID, "_url1", true, ',');
    $name1 = get_post_meta($post->ID, "_name1", true);
    $role2 = get_post_meta($post->ID, "_role2", true);
    $url2 = get_post_meta($post->ID, "_url2", true, ',');
    $name2 = get_post_meta($post->ID, "_name2", true);
    $role3 = get_post_meta($post->ID, "_role3", true);
    $url3 = get_post_meta($post->ID, "_url3", true, ',');
    $name3 = get_post_meta($post->ID, "_name3", true);
    ?>
    <ul class="credits">
        <?php if(!empty($role1)) echo '<li>' . $role1 . '</li>'; ?>
        <?php if(!empty($url1) && !empty($name1)) echo '<li><a href="' . $url1 . '" target="_blank">' . $name1 . '</a>,</li>'; ?>
        <?php if(!empty($role2)) echo '<li>' . $role2 . '</li>'; ?>
        <?php if(!empty($url2) && !empty($name2)) echo '<li><a href="' . $url2 . '" target="_blank">' . $name2 . '</a>,</li>'; ?>
        <?php if(!empty($role3)) echo '<li>' . $role3 . '</li>'; ?>
        <?php if(!empty($url3) && !empty($name3)) echo '<li><a href="' . $url3 . '" target="_blank">' . $name3 . '</a>,</li>'; ?>
    </ul>
    

    I didn't understand where you want to put the punctuation.