• Resolved websters

    (@websters)


    Hello there!

    This is my first attempt to create a custom theme and I’m currently working on my single.php. While I’m in the loop I want to display a custom field wrapped by a div with a specific class, but only if the custom field has a value. After some research, I’ve included this piece of code in my functions.php:

    //Custom Fields 
    
    function blog_short_info(){
    global $post;
    echo get_post_meta($post->ID, 'Blog_Post_Short_Info', true);
    }
    add_action('the_content','blog_short_info');

    and this one in my single.php:

    <?php if ( blog_short_info() ) { ?>
    	<div class="blog-short-info">
    		<?php blog_short_info();?>
    	</div>
    <?php } ?>

    Btw, If I remove my if statement the blog_short_info function works just fine, but as soon I include this if statement everything goes sideways!
    Any ideas of what I’m doing wrong?

    Thanks in advance!

    P.S: I’m still working on localhost, so unfortunately I can’t provide a link

Viewing 2 replies - 1 through 2 (of 2 total)
  • Try this…

    //Custom Fields 
    
    function blog_short_info(){
    global $post;
    return get_post_meta($post->ID, 'Blog_Post_Short_Info', true);
    }
    add_action('the_content','blog_short_info');
    <?php if ( blog_short_info() ) { ?>
    	<div class="blog-short-info">
    		<?php echo blog_short_info();?>
    	</div>
    <?php } ?>
    Thread Starter websters

    (@websters)

    @rajesh Soni Thank you very much for your help! It worked like a charm, but may I ask you why I needed to use return in the blog_short_info() function instead of echo and use the echo when I was calling the function inside the if statement?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘if statement for get_post_meta() or how to display custom field if it exists’ is closed to new replies.