WordPress shortcode: Display the loop

September 23, 2009 at 9:10 am

By default, the loop is the easiest way to display WordPress posts. Though, we can create a shortcode that will make post displaying ven simpler. Perfect for sites who are using WordPress as a CMS!

Simply paste this code in your functions.php file. Or if you want, you can use it in a plugin.

function myLoop($atts, $content = null) {
		"pagination" => 'true',
		"query" => '',
		"category" => '',
	), $atts));
	global $wp_query,$paged,$post;
	$temp = $wp_query;
	$wp_query= null;
	$wp_query = new WP_Query();
	if($pagination == 'true'){
		$query .= '&paged='.$paged;
		$query .= '&category_name='.$category;
		$query .= $query;
	<h2><?php echo $category; ?></h2>
	<ul class="loop">
	<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
		<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php echo $thumbnail_image; the_title(); ?></a></li>
	<?php endwhile; ?>
	<?php if(pagination == 'true'){ ?>
	<div class="navigation">
	  <div class="alignleft"><?php previous_posts_link('« Previous') ?></div>
	  <div class="alignright"><?php next_posts_link('More »') ?></div>
	<?php } ?>
	<?php $wp_query = null; $wp_query = $temp;
	$content = ob_get_contents();
	return $content;
add_shortcode("loop", "myLoop");

Once your functions.php file is saved, you can display a loop :

[loop category="news" query="" pagination="false"]

Note that this code have been created to been used in pages. It have some oddity when used in a post.

Thanks to John Turner for this great piece of code!