Break And Then Continue The Loop In WordPress

Break And Then Continue The Loop In WordPress

By default the loop is used to display wordpress posts. Using the loop, wordpress display each post from the blog to the current page. The loop can be styled with HTML and PHP code, which will be processed for each blog post.

For example on the following code (let’s say we have 3 posts in our blog):

[php] <?php if (have_posts()) : while (have_posts()) : the_post();>
<article id=”post-<?php the_ID(); ?>”>
<h2><?php the_content(); ?></h2>
<p><?php the_content(); ?></p>
</article>
<?php endwhile; endif; ?>
[/php]

the loop will output:

[html] <article id=”1″>
<h2>Title of post 1</h2>
<p>Content of post 1</p>
</article>
<article id=”2″>
<h2>Title of post 1</h2>
<p>Content of post 1</p>
</article>
<article id=”3″>
<h2>Title of post 1</h2>
<p>Content of post 1</p>
</article>
[/html]

Now…let’s get our hands dirty!

But there comes a time, when you want more then just to display each post with the same HTML tags. Maybe you want the first post a little bigger, the second to have a bigger title and so on. There are many many possibilities and combinations. And then you ask yourself: How can I do that, because the standard loop, only output posts and repeat the HTML tags within the loop?

Well..you can…you can make some conditional PHP comments, and style each post just the way you want. Here is how you can do it:

[php]

<?php
while ($wp_query->have_posts()) :
$wp_query->the_post();
if($wp_query->current_post <= 1){ ?>
<div class=”post-1″>
<h2><?php the_title() ;?></h2><!–Add any HTML here as this will apply for the first post only–>
<?php the_content(); ?>
</div>
<?php }
if($wp_query->current_post <= 2){ ?>
<div class=”post-2″>
<h2><?php the_title() ;?></h2><!–Add any HTML here as this will apply for the second post only–>
<?php the_content(); ?>
</div>
<?php }
if($wp_query->current_post >= 3){ ?>
<div class=”rest-of-the-posts”>
<h2><?php the_title() ;?></h2><!–This HTML will apply from the third post up–>
<?php the_content(); ?>
</div>
<?php }
endwhile;?>

[/php]

If you take a look at the code above, you can see that you can make a conditional comment for each post you want, and the HTML/PHP will be applied to that post only.

That’s all. Happy coding!

Leave a reply

0
Connecting
Please wait...
Send a message

Sorry, we aren't online at the moment. Leave a message.

Your name
* Email
* Describe your issue
Chat now

Need more help? Save time by starting your support request online.

Your name
* Email
* Describe your issue
We're online! Ask us anything!
Feedback

Help us help you better! Feel free to leave us any additional feedback.

How do you rate our support?