Multiple Loops in Wordpress

line Tags: ,

I wanted to run the wordpress loop on my php page more than once, & I don’t know if I’m the only person, but I found the offical multiple look example hard to swallow.

Google found is nima’s how to which was useful, but I wanted to take it further; the problem was I wanted a function.

This is what I came up with:

<?php
require(’path_to_wordpress/wp-blog-header.php’);
?>

<?php
function show_posts_from_cat($MYCAT){

?>

<ul>
<?php if (have_posts()) : ?>

<?php $my_query = new WP_Query(”category_name=$MYCAT”); ?>

<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li>

<span class=”my-post-title”>
<span id=”post-<?php the_ID(); ?>”><a href=”<?php the_permalink() ?>” rel=”bookmark” title=”Permanent Link to <?php the_title(); ?>”><?php the_title(); ?></a></span>
<!–
<?php trackback_rdf(); ?>
–>
</span>
<small><?php the_time(’jS F Y’) ?> <!– by <?php the_author() ?> –></small>
</li>

<?php endwhile; ?>

<?php else : ?>

<h2 class=”center”>Not Found</h2>
<p class=”center”><?php _e(”looks like there aren’t any related posts.”); ?></p>

<?php endif; ?>

</ul>

<?php
}
?>

So here’s what I found, if you just run the wordpress loop twice, the second time you run it, it’ll fail :s so my function creates a new object each time you run the loop. The object is then used to display the results, the benefit being ,each time you call the function it over-writes the object with the new results, allowing you to call the function as many times as you like, and generating fresh results every time :D

function usage: show_posts_from_cat(”Category_name”);

Good luck, let me know if you have ant problems.

nick

 

Got something to say?

 

Some other things that might interest you...

---