WordPress provides plenty of flexibility with four or five ways to loop: These are
Each of these looping methods is useful in a variety of situations, these four techniques enable simple loops, multiple loops, and custom loops in your WordPress theme template. A good place for looking into default loop, is in your theme's index.php
file. Its purpose is to loop through the posts stored in the database and echo their contents to the browser, using WordPress' template tags.
The Default Loop
The default WordPress loop looks something like this
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php the_content(); ?>
</div>
<?php endwhile; ?>
<div class="navigation">
<div class="next-posts"><?php next_posts_link(); ?></div>
<div class="prev-posts"><?php previous_posts_link(); ?></div>
</div>
<?php else : ?>
<div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
<h1>Not Found</h1>
</div>
<?php endif; ?>
Loop with WP_Query()
For complete control over the customization of any number of loops, WP_Query is the way to go. With WP_Query
, we don’t need the $query_string
variable. In addition to using WP_Query
to customize the default loop, we can also use it to create and customize multiple loops. Here is a basic example:
<?php // Loop 1
$first_query = new WP_Query('cat=-1'); // exclude category
while($first_query->have_posts()) : $first_query->the_post();
...
endwhile;
wp_reset_postdata();
// Loop 2
$second_query = new WP_Query('cat=-2'); // exclude category
while($second_query->have_posts()) : $second_query->the_post();
...
endwhile;
wp_reset_postdata();
// Loop 3
$third_query = new WP_Query('cat=-3'); // exclude category
while($third_query->have_posts()) : $third_query->the_post();
...
endwhile;
wp_reset_postdata();
?>
Each of these additional loops may be placed anywhere in your theme template – no need to line them up sequentially. For example, one loop may be placed in your sidebar, another in your footer, and so on. And with the output of each loop easily modified via the parameters, any loop configuration is possible. Use WP_Query
for creating multiple, customized loops. By setting up additional instances of WP_Query
in your theme, you can create any number of multiple loops, and customize the output of each.
Loop with get_posts()
This code creates a loop of all posts except those in the excluded category. Of course, excluding a category is just one way to customize your additional, static loops. By using any of the same parameters accepted by WP_Query
and query_posts
, it's possible to create loops that display just about anything. Use the get_posts()
function to easily create additional, static loops anywhere in your theme. get_posts
accepts the same parameters as query_posts
, and is perfect for adding static, custom loops to your sidebar, footer, or anywhere else.
No comments:
Post a Comment