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
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>
<?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>
<div><?php previous_posts_link('« Previous') ?></div>
<div><?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 the loop using WordPress shortcode:
[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!
