Grow your CSS skills. Land your dream job.

WordPress – If Statement

  • # July 6, 2012 at 12:11 am

    I am using a custom meta box to post a description however, it outputs

    when there is no content. How can I write an if statement so if there is content, it will post, otherwise output nothing?

    < ?php
    // usually needed
    global $custom_metabox;
    // get value directly
    $custom_metabox->the_value('description');
    ?>

    # July 6, 2012 at 12:17 am

    Try this

    < ?php

    global $custom_metabox;

    if (($value = $custom_metabox->the_value('description')) !== '') {
    echo '

    ' . $value . '

    ';
    }

    ?>
    # July 6, 2012 at 12:22 am

    @SgtLegend It still outputs

    # July 6, 2012 at 12:24 am

    See what the output value is by using the following as it sounds like white space may be present in the value.

    echo 'Value: ' . $custom_metabox->the_value('description');
    # July 6, 2012 at 12:26 am

    @SgtLegend That outputs the following

    Value: 
    # July 6, 2012 at 12:28 am

    Sorry, forgot to wrap it in a function.

    echo 'Value: ' . strlen($custom_metabox->the_value('description'));
    # July 6, 2012 at 12:30 am

    @SgtLegend

    Value: 0
    # July 6, 2012 at 12:32 am

    You could try:

    $desc = $custom_metabox->the_value('description');

    if (!empty($desc)):
    echo $desc;
    endif;
    # July 6, 2012 at 12:36 am

    @ChrisxClash, Ah I think that worked but how would I incorporate:

    # July 6, 2012 at 12:52 am

    Is this what you mean?

    < ?php
    $desc = $custom_metabox->the_value('description');

    if (!empty($desc)): ?>

    < ?php echo $desc; ?>


    < ?php endif; ?>
    # July 6, 2012 at 12:59 am

    @ChrisxClas Exactly although it’s not working.

    # July 6, 2012 at 1:06 am

    What’s happening?

    # July 6, 2012 at 1:08 am

    @ChrisxClash Nothing. It just outputs the text without the markup

    # July 6, 2012 at 1:19 am

    It’s only echoing $desc without the p tags?

    # July 6, 2012 at 1:23 am

    @ChrisxClash Correct.

Viewing 15 posts - 1 through 15 (of 31 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".