WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] How do I show custom meta fields or alternate content if empty? (6 posts)

  1. aproimage
    Member
    Posted 4 years ago #

    Hi,

    I've been looking round the codex and Google, trying to find clues about how to achieve this, but I fear my PHP knowledge leaves a little to be desired.

    Basically my blog uses custom meta fields to display additional information on posts, however if these fields are left empty I want to hide the empty div that would otherwise contain the meta content and replace this with alternative content.

    I know this is probably grass roots 'if, else' stuff but I'm not so hot on the exact syntax, any help would be greatly appreciated.

    I currently call meta info using <?php echo get('analystnotes')?>

    Thanks, Rob

  2. MichaelH
    Member
    Posted 4 years ago #

    If you are using Custom Fields and we are talking about displaying posts in a Loop this will try to find a custom field and then do something if the custom field exists or doesn't exist

    <?php
    $cf = get_post_meta($post->ID, 'analystnotes', true);
    if ($cf){
      //do your div thing here
    } else {
      //do nothing or whatever you need when no custom field was found
    }
    ?>

    Related:
    Stepping Into Template Tags
    Stepping Into Templates
    Template Hierarchy

  3. aproimage
    Member
    Posted 4 years ago #

    Thanks Michael I really appreciate this, I now have the following code

    <?php
     $analystnotes = get_post_meta($post->ID, 'analystnotes', true);
     if ($analystnotes){ echo get ('analystnotes');
     } else {
     echo '<div class="analysisnone">BLANK</div>';
     }
     ?>

    This is largely working as I would like, but is there a way to wrap the get ('analystnotes')statement in a div, I know this is more a general PHP thing but haven't managed to figure it out.

    Thanks again

  4. MichaelH
    Member
    Posted 4 years ago #

    Guessing your are asking something like what is used in the WordPress Default theme's wp-content/themes/default/index.php

    <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
  5. aproimage
    Member
    Posted 4 years ago #

    Not sure that's quite what I'm after, I would just like to be able to apply a div class to the if statement

  6. aproimage
    Member
    Posted 4 years ago #

    All sorted, thanks, added an additional instance of the code to handle div classes.

    Really appreciated, thanks.

Topic Closed

This topic has been closed to new replies.

About this Topic