• Hello,
    I’m trying to create a PHP “if” statement that places the data from custom fields into a div with css, but if there are no custom fields applied to that post, then the div is displayed with static text.

    Here’s what I have right now:

    <?php if(the_meta()): ?>
    			<div id="portfolio-meta">
    				<p id="projmeta-head">Project Information:</p>
    				<?php the_meta(); ?>
    			</div>
    
    			<?php else: ?>
    
    			<div id="portfolio-meta">
    				<p id="projmeta-head-negative">This item has no information associated with it. Sorry.</p>
    			</div>
    
    			<?php endif; ?>

    However, when wordpress comes across a post with custom fields, instead of displaying the div with the meta data in it, the div under “else” is displayed, and the metadata is displayed above the div.

    What’s wrong with this picture? Also, I’m very new at writing PHP, so this is my attempt at trying to figure things out after doing some research.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The function the_meta() isn’t meant to return anything, it always displays the meta keys, even if you put it inside if().
    So on this line of your script
    <?php if(the_meta()): ?>
    the custom fields are always displayed, the_meta returns NULL, the condition evaluates to false and the execution hops to these lines

    <?php else: ?>
    
        <div id="portfolio-meta">
        <p id="projmeta-head-negative">This item has no information associated with it. Sorry.</p>
    			</div>
    
    			<?php endif; ?>

    and displays the message “This is no information…”

    The part of the script between if and else is never executed.

    There is a little function that should do what you want

    $post_meta_keys = get_post_custom_keys($post->ID) ;
    $nonprotected_meta_keys = 0;
    foreach ( $post_meta_keys as $key ) {
        if( is_protected_meta($key)){
                continue;
            }
            else $nonprotected_meta_keys++;
        }
    if($nonprotected_meta_keys > 0) :
    the_meta();
    else : ?>
            <p>No meta here!</p>
        <?php endif;

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘PHP if statement for custom fields.’ is closed to new replies.