Limit to One Post on WordPress Front Page

Let’s say you have a WordPress blog. You only want one post to appear on the front page of that blog. But, you want all other pages (e.g., the second page, category pages, monthly archives, etc.) to display more than one (be it 5, 10, or whatever you chose on your “Reading Settings” page). The first part is easy, the latter has a few pitfalls to be aware of.

First, we’re going to call query_posts to modify the query a bit. We only want this on the home page, so we wrap it in an if statement:

global $wp_query;
if ( is_home() && !is_paged() ) {
  query_posts(
    array_merge(
      $wp_query->query,
      array('posts_per_page'=>1)
    )
  );
}

is_home() will be TRUE if you’re on the main blog page; !is_paged() verifies that we’re on the first page (because is_home() is still TRUE on subsequent pages (e.g.http://example.com/page/2/)).
Continue reading “Limit to One Post on WordPress Front Page”

Make a New WordPress Loop with query_posts

The “Useful WordPress Function of the Day” award goes to query_posts. This function can be used to:

  • Revise the query that WordPress forms from the URL, so you can change the sorting of posts, exclude certain categories, etc.
    query_posts($query_string . "&order=ASC&category_name=Libraries");

    This takes the current query and sorts it in ascending order, limiting the results to posts in the “Libraries” category.

  • Create custom queries, either for public-facing pages or in administration plugins.
    query_posts(array(
      "category__in" => array(1,3),
      "posts_per_page" => -1,
      "author" => 5
    ));

    This query grabs all the posts by author 5 in categories 1 or 3.

After calling query_posts, you can use your standard WordPress loop, along with all the template tags it makes available, in your template or plugin.