Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a second loop to a Wordpress theme on a separate page

I'm trying to add two loops to a theme on two separate pages: home and blog.

Blog is basically an index of the posts. It's what most Wordpress pages default to as a home page. To accomplish this I went to "reading settings" and set "front page displays" as 'static' with "front page" set to a Home page I set up in Wordpress pages and "posts page" set to a Blog page.

Now the problem is that when I add the loop to the Home page, it doesn't work, presumably because I have posts page set to a different page.

So how do I get the loop to work on the Home page as well as the blog page? Btw, the Home page loop is just post title + date + maybe excerpts. Do I need to completely rework the theme or is this is just not a possibility under Wordpress?

Oh and the loop I'm using is:

<?php if(have_posts()) : ?>
        <?php while(have_posts()) : the_post() ?>
like image 368
Ben Moseley Avatar asked Aug 11 '10 06:08

Ben Moseley


1 Answers

There are at least three wayst to run custom queries in WordPress.

Query_posts() can define the query string of your second loop. It is easy and very common to do. This code is a basic structure I copied from the codex page for query_posts():

//The Query
query_posts('posts_per_page=5');

//The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
 ..
endwhile; else:
 ..
endif;

//Reset Query
wp_reset_query();

You can also use get_posts() which is similar.

<ul>
 <?php
 global $post;
 $myposts = get_posts('numberposts=5&offset=1&category=1');
 foreach($myposts as $post) :
   setup_postdata($post);
 ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
 <?php endforeach; ?>
 </ul> 

Both functions accept a number of arguments that are explained on the query_posts function reference page. The arguments shown above are only examples. The list of available args is long.

A third method available to you is to instantiate another instance of the WordPress Query object (WP's main query method). Query_posts and get_posts both run a second call to the database after WordPress runs the default wp_query. If you are super concerned about performance or reducing db hits, I suggest learning how you can interact with wp_query to modify the default query before it is run. The wp_query class provides a number of simple methods for you to modify the query.

Good Luck!

like image 184
kevtrout Avatar answered Sep 25 '22 13:09

kevtrout