
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!

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) {
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.
Thanks to John Turner for this great piece of code!
6 Responses
Awesome,
Could you please tell me how to add limit to this category specified loop.
I want 3 items to display at front.
Thanks
Can one use the regular loop inside a shortcode? eg: if have posts : while have posts : the_post , etc…?
Awesome! Just a quick tip. I’m using this on a WP-Framework child theme. In order to get the regular loop as your output simply throw in:
get_template_part( ‘loop’, ‘archive’ );
Lucas!!!! You have no idea how much your post helped me out!!! After 3 long days of no sleep and pulling my hair out trying to accomplish a short code loop using the main loop, your post saved my life!!!!!!!!!!!!!!!!!!!
is it possible to do the same for custom post types? Ive been searching unsuccesfully for a way to display paginated results of a custom post type
Hello, How can I add more attributes like, “order”, “posts_per_page”, etc. Thanks!
Trackbacks: