This post is to summarize and present the code snippets of the most WordPress fundamental: the loop.
1. Set up index.php
<?php get_header(); ?> <div id="posts-container"> // loop starts here </div> <?php get_sidebar(); ?> <?php get_footer(); ?>
2. Simplest loop
if (have_posts()) : while (have_posts()) : the_post(); the_content(); endwhile; endif;
Within the while loop:
- Function the_post() makes the current item in the posts collection available for use inside this iteration.
- Template tag the_content() returns the post content.
3. Default loop
<?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 : ?> <h1>No posts found</h1> <?php endif; ?>
4. Insert customized content before the nth post
<?php if (have_posts()) : ?> <?php $count = 0; ?> <?php while (have_posts()) : the_post(); ?> <?php $count++; ?> <?php if ($count == n) : ?> //customized block of content here, might be Ad, video, image, etc. <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_content(); ?> <?php else : ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_content(); ?> <?php endif; ?> <?php endwhile; ?> <?php endif; ?>
5. Remove specific category(ies)
<?php query_posts('cat=-5, -7, -9'); ?> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <?php the_content(); ?> <?php endwhile; ?>
Above example removes the post(s) with categories IDs 5, 7, and 9. Note the drawbacks of using query_post() such as altering the main loop and pagination › ›
References:
- http://codex.wordpress.org/The_Loop
- http://codex.wordpress.org/The_Loop_in_Action
- http://wp.smashingmagazine.com/2009/06/10/10-useful-wordpress-loop-hacks