Support » Fixing WordPress » PHP Code for “If has meta data for this value, then show this…if not, do not”

  • So just need to check if there is a value in this post for a designated custom field and post if there is but don’t post anything there if there is not.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Hi,

    I spent some hours trying to figure this out myself, first of all you need to change the function the_meta() as pointed out by Morgaine in this thread: http://wordpress.org/support/topic/138355.

    Code:

    function the_meta() {
    	global $id;
    
    	if ( $keys = get_post_custom_keys() ) {
    		foreach ( $keys as $key ) {
    			$keyt = trim($key);
    			if ( '_' == $keyt{0} )
    				continue;
    			echo "<ul class='post-meta'>\n";
    			$values = array_map('trim', get_post_custom_values($key));
    			$value = implode($values,', ');
    			echo "<li><span class='post-meta-key'>$key:</span> $value</li>\n";
    			echo "</ul>\n";
    		}
    	}
    }

    Then add this piece of code to your template files (I use this in my single.php, but where you want to put it is obviously up to you and your design):
    <?php if(the_meta()) { the_meta(); } ?>

    Hope this helps!

    Paul

    Thanks, just saved me a bunch of time. I’ll try to make this work.

    function the_meta() {
    	global $id;
    
    	if ( $keys = get_post_custom_keys() ) {
    		foreach ( $keys as $key ) {
    			$keyt = trim($key);
    			if ( '_' == $keyt{0} )
    				continue;
    			echo "<ul class=\"post-meta\">\n";
    			$values = array_map('trim', get_post_custom_values($key));
    			$value = implode($values,', ');
    			echo "<li><span class=\"post-meta-key\">$key:</span> $value</li>\n";
    			echo "</ul>\n";
    		}
    	}
    }

    A little “cleaner” as it follows the semantics of the other pieces of code closer.

    FYI: note that the function adds a : next to your key. This means if you add your key as “Todays book:” it will become “Todays book::” on your website.

    PW

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘PHP Code for “If has meta data for this value, then show this…if not, do not”’ is closed to new replies.