September 7

Break And Then Continue The Loop In WordPress

0  comments

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!


Tags

break, continue, html, loop, style, wordpress


You may also like

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Get in touch

Name*
Email*
Message
0 of 350