[wp-hackers] How you handle empty metadata

Jackson Whelan jw at jacksonwhelan.com
Fri Aug 31 10:40:10 UTC 2012

On 8/30/12 5:22 PM, Diana K. C wrote:
> I created a filter that places content on posts and pages but since I'm combining some tags such <li> etc I endeup with silly empty tags if any value is provided  :(
> One or two ok check with (!empty)  but I have ten values, what is the best pratice?!
I won't claim this is 'best practice', but... I use a handy little 
function to check if a post meta value is set before echoing.

    // In my functions.php file

    function echo_if_meta( $arr, $key, $before = '', $after = '' ) {

         if( $text = $arr[$key][0] )
             echo $before . $text . $after;


    // In my template

    <?php $meta = get_post_custom(); ?>
         <?php echo_if_meta( $meta, '_my_key', '<li>My Key: ', '</li>'); ?>
         <?php echo_if_meta( $meta, '_my_key_2', '<li>My Key 2: ',
    '</li>'); ?>

You could adapt this for a returned value in a filter.

In short, write yourself a little function to check if the value is set 
and return null if not, and return the value wrapped in start and end 
tags if set.

Hope that helps,


*Jackson Whelan* / WordPress Web Design & Development

Pittsford, Vermont / 802.483.4050
jacksonwhelan.com <http://jacksonwhelan.com?s=e> / jw at jacksonwhelan.com 
<mailto:jw at jacksonwhelan.com>

More information about the wp-hackers mailing list