Display the loop using wordpress shortcode

September 23, 2009 · Print This Article

The loop is the easiest way to display WordPress posts, perfect for those sites who are using WordPress as a CMS. But we can create a shortcode that will make post displaying simpler.

Use this shortcode below to create a loop on a page, post or sidebar. Just use template tags and html like you would in a normal loop to create your layout. The sample below displays an unordered list with titles and links to the post.

Just paste code in your functions.php file. Or if you want, you can use it in a plugin.
// The Loop
/*
* Usage: [loop category="news" query="" pagination="false"]
*/
function myLoop($atts, $content = null) {
extract(shortcode_atts(array(
"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;
}
if(!empty($category)){
$query .= '&category_name='.$category;
}
if(!empty($query)){
$query .= $query;
}
$wp_query->query($query);
ob_start();
?>
<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; ?>
</ul>
<?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>
</div>
<?php } ?>
<?php $wp_query = null; $wp_query = $temp;
$content = ob_get_contents();
ob_end_clean();
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.


Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.