If and Else in single.php for showcasing multiple categories

44 Views Asked by At

I'm trying to show 3 different layouts for 3 different categories in WordPress but failing as the 2nd category output shows the 3rd category too:

Where am I going wrong in giving the conditions? Please help.

Line 12 <?php endif ?> feels like it shouldn't be there but removing it gives a blank page.

<div class="details">
    <div class="container">
        <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
            <?php if(in_category('cat1')): ?> 
                <div><h1><?php the_title(); ?></h1></div>
                <p>1</p>
            <?php else: ?>
            <?php if(in_category('cat2')): ?>
                <div><h1><?php the_title(); ?></h1></div>
                <p>2</p>
            <?php else: ?>
            <?php endif ?>
                <div><h1><?php the_title(); ?></h1></div>
                <p>3</p>
            <?php endif ?>  
            <?php endwhile; else: ?>
            <p>There no posts to show</p>
        <?php endif; ?>
    </div>
</div>

Output for Cat1 is correct:

<h1>Cat 1 Title</h1>
<p>1</p>

Output for Cat2 is not correct and showing Cat3 too:

<h1>Cat 2 Title</h1>
<p>2</p>
<h1>Cat 3 Title</h1>
<p>3</p>

Output for Cat3 is correct though:

<h1>Cat 2 Title</h1>
<p>3</p>
1

There are 1 best solutions below

0
Wh1t3rabbit On

You have an else followed by an endif. This is the same as else {} (does nothing).

I have corrected the indentation in your original code and you can now see why it showing cat2 and 3 together:

<div class="details">
    <div class="container">
        <?php
            if (have_posts()) {
                while (have_posts()) {
                    the_post();
                    if(in_category('cat1')) {
                        echo "<div><h1>".the_title()."</h1></div>";
                        echo "<p>1</p>";
                    } else {
                        if(in_category('cat2')) {
                            echo "<div><h1>".the_title()."</h1></div>";
                            echo "<p>2</p>";
                        } else {
                        }
                        echo "<div><h1>".the_title()."</h1></div>";
                        echo "<p>3</p>";
                    }
                }
            } else {
                echo "<p>There no posts to show</p>";
            }
        ?>
    </div>
</div>