0

I am currently working on my home.php file for my theme, and I'm planning on displaying my the last Blog posts in a "grid view", so that there are 4 containers in a row, containing the title and some more information.

I tried out some things, but nothing worked the way I wanted it to. The last thing I did was putting a for loop like this:

<?php
    for ($x = 1; $x <= 6; $x++) :
?>
        <div id="home_post_<?php echo $x ?> " class="home_post">
            <?php
                if(have_posts()) :
                    while(have_posts()) : the_post();
                        get_template_part('template-parts/content', 'home');
                    endwhile;
                endif;
            ?>
        </div>
<?php
    endfor;
?>

Around my loop, but that way, every new div is filled with the first overall Blogpost, so this is not the way to do it.

Is there a clever way to work with a loop that "generates" divs or am I just on the wrong track?

1

It's a little bit hard to guess, what exactly do you want to achieve (you've mentioned something about four posts in a row and then there is number 6 in your for loop), but...

If you want to display only 4 posts in your loop, then you can use current_post field of $wp_query, so the loop may look like this:

<?php while ( have_posts() and $wp_query->current_post < 4) : the_post(); ?>
    <div id="home_post_<?php echo $wp_query->current_post ?>">
        <?php get_template_part('template-parts/content', 'home'); ?>
    </div>
<?php endwhile; ?>
// you don't do anything if there are no posts, so there's no point in checking if (have_posts())

Another thing worth to remember is that if you'd like to show only 4 posts on your home, then it's a good idea to modify query accordingly - so it doesn't get redundant posts.

| improve this answer | |
0

Solved it by myself, here is how i did it:

       <?php

            $x = 0;
        if(have_posts()) : while(have_posts() and $x <=5) : the_post(); ?>
            <div id="home_post_<?php echo $x ?>"> <?php
            get_template_part('template-parts/content', 'home');
                ?> </div> <?php
            $x++;
        endwhile;
        endif;
        ?>
| improve this answer | |
  • You don't need to use your custom counter ($x). Take a look at my answer. – Krzysiek Dróżdż Mar 30 '18 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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