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.

Read More

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() ?>

Related posts

Leave a Reply

2 comments

  1. 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!

  2. It is possible that WordPress does not start a loop for you because you use a static page. But if this static page is defined in your theme (since you include the PHP code to display the loop, I assume it is), you can always start a new loop there yourself. Just call query_posts yourself, and your code should start working.