Forums

Hide a custom field if is empty (7 posts)

  1. euforico
    Member
    Posted 3 years ago #

    Hi:

    I have a custom field called "my_name", if this custom field is empty want to hide. How can i do this?

    For example the code is <?php echo get_post_meta($post->ID, 'my_name', true); ?>

    Thanks!

  2. @mercime
    Member
    Posted 3 years ago #

    Custom field that is blank will not show up in post with your echo. Why, did something appear in your post even when you left custom field blank?

  3. rarareddog
    Member
    Posted 3 years ago #

    I think what euforico means is that he has the custom field set up for the src of an image for example.

    <img src="<?php echo get_post_meta($post->ID, 'my_name', true); ?>" alt="Alt Text" />

    I know what I want but my php code is very inadequate.

    You need something like:

    if the custom field is not empty, display this:

    <img src="<?php echo get_post_meta($post->ID, 'my_name', true); ?>" alt="Alt Text" />

    if it is empty, display this:

    <img src="http://www.blog.com/path-to-generic-image.jpg" alt="Alt Text" />

  4. euforico
    Member
    Posted 3 years ago #

    Thanks @rarareddog
    This is the point. If the custom fied "my_name" is empty, then change the information.

  5. MichaelH
    Volunteer
    Posted 3 years ago #

    I believe something like this would work:

    <?php
    $myname = get_post_meta($post->ID, 'my_name', true);
    if ( $myname ) {
     echo 'there is a custom field value';
    }
    else {
    echo 'no custom field value';
    }
    ?>
  6. Dgold
    Member
    Posted 3 years ago #

    Here is a great tutorial on how to do it,
    http://epicalex.com/default-custom-fields/

    The code is basically this, (pretty much the same idea as what MichaelH posted above but I think this does it the other way around -- if custom field is empty, show default image, if custom field is not empty then show the custom field value)

    <?php
    $thumb = get_post_meta($post->ID, 'Homepage Image', true);
    if ($thumb == '')
    { ?>
    
    <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
    <img src="http://domain.com/images/defaultimage.jpg"
    alt="<?php the_title(); ?>"/>
    </a>
    
    <?php } else { ?>
    <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
    <img src="<?php echo $thumb; ?>" alt="<?php the_title(); ?>"/>
    </a>
    <?php } ?>
  7. mtonumaa
    Member
    Posted 2 years ago #

    This displays Website link only when custom field is filled, otherwise nothing.

    <?php if($view_web_site !== '') { ?>
    <a href="<?php echo $view_web_site; ?>">Website</a>
    <?php } ?>

Topic Closed

This topic has been closed to new replies.

About this Topic