0

I created some code to return attachment categories, that looks like:

<?php
    // Attachment Categories
    $categories = get_the_category($attachment->ID);
    if ($categories) {
?>
    <ul>
        <?php foreach ($categories as $category) { ?>
            <?php if ($category->name !== 'Slides') if ($category->name !== 'Uncategorized') { ?>
                <li><?php echo $category->name; ?></li>
            <?php } ?>
        <?php } ?>
    </ul>
<?php } ?>

I am trying to add an else, but for some reason the else doesn't work with the two if statements...if I remove one if statement, the else works.

The code with the else looks like:

<ul>
    <?php foreach ($categories as $category) { ?>
        <?php if ($category->name !== 'Slides') if ($category->name !== 'Uncategorized') { ?>
            <li><?php echo $category->name; ?></li>
        <?php } else { ?>
            <li>Unknown</li>
        <?php } ?>
    <?php } ?>
</ul>

Can anyone point me in the right direction?

Thanks,
Josh

1

2 Answers 2

0

That's not how you chain multiple conditions with an if statement. Try this

<ul>
    <?php foreach ($categories as $category) { ?>
        <?php if ($category->name !== 'Slides' && $category->name !== 'Uncategorized') { ?>
            <li><?php echo $category->name; ?></li>
        <?php } else { ?>
            <li>Unknown</li>
        <?php } ?>
    <?php } ?>
</ul>
3
  • This is a great answer, unfortunately Sanjeev submitted a response first, thanks for your suggestion! Jul 19, 2017 at 13:47
  • Timing says mine was first, not really worried about though.
    – mrben522
    Jul 19, 2017 at 14:06
  • You're right, my apologies, I've updated my selection :-) Jul 19, 2017 at 14:09
0
<ul>
    <?php foreach ($categories as $category) { ?>
        <?php if ($category->name !== 'Slides' && $category->name !== 'Uncategorized') { ?>
            <li><?php echo $category->name; ?></li>
        <?php } else { ?>
            <li>Unknown</li>
        <?php } ?>
    <?php } ?>
</ul>

Bro use && or || Operator according to your requirement as i wrote above.

Not the answer you're looking for? Browse other questions tagged or ask your own question.