Forums

PHP Code for "If has meta data for this value, then show this...if not, do not" (5 posts)

  1. benfranklin
    Member
    Posted 1 year ago #

    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.

  2. PaulWicking
    Member
    Posted 1 year ago #

    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

  3. benfranklin
    Member
    Posted 1 year ago #

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

  4. PaulWicking
    Member
    Posted 1 year ago #

    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.

  5. PaulWicking
    Member
    Posted 1 year ago #

    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

Topic Closed

This topic has been closed to new replies.

About this Topic