if/else in php and echo html code

In the following code, I’m checking that if I’m on my home page of the website, then I will shift the columns by an offset of 2 toward right and for all other pages I shouldn’t have any offset. I’m trying to implement this but I’m getting an error. It would be great if you can give me a hint. Thanks!

    <?php if (is_front_page() ) {
        echo '<div class="col-md-8 la-content-inside col-md-offset-2">';
        while ( have_posts() ) { the_post(); }
    } else {
        echo '<div class="col-md-8 la-content-inside">';
        while ( have_posts() ) { the_post(); }
    }
    ?>

                <?php get_template_part( 'content', 'page' ); ?>

            <?php endwhile; // end of the loop. ?>
        </div>

Related posts

3 comments

  1. In your code you are opening while block in if & else block & closing the endwhile after condition blocks.

    try using

    <?php  
    if (is_front_page() ) {
        echo '<div class="col-md-8 la-content-inside col-md-offset-2">';
        while (have_posts()) : the_post(); 
            get_template_part( 'content', 'page' );
        endwhile; // end of the loop.
    }else {
        echo '<div class="col-md-8 la-content-inside">';
        while (have_posts()) : the_post();
            get_template_part( 'content', 'page' );
        endwhile; // end of the loop. 
    }
    ?>
    
  2. Let’s start with cleaning up your code. I’m writing the code over several lines so it stays understandable for the one asking the question. (Yes, you could write it more efficient)

    <?php
    echo '<div class="col-md-8 la-content-inside';
    // frontpage exception
    if(is_front_page()) {
         echo ' col-md-offset-2';
    }
    echo '>';
    
    while(have_posts()) {
        the_post();
        get_template_part( 'content', 'page' );
    }
    echo '</div>';
    ?>
    

    If this generates an error. Please copy paste the error as comment in this answer.

  3. try below short code.. will for you..

    <div class="col-md-8 la-content-inside <?php echo (is_home() ? 'col-md-offset-2' : '' );?> ">
     <?php while (have_posts()) : the_post(); 
          get_template_part( 'content', 'page' );
       endwhile; // end of the loop.
     ?>
     </div>
    

    you need to user is_home() function.. for front page.

Comments are closed.