Random Post: 1. Eagle Eye - $29.2M
RSS .92| RSS 2.0| ATOM 0.3
  • Home
  • Contact Us
  • deviantART
  • Newsletter
  • Online Booking
  • Registration
  • Tell A Friend
  •  

    Template Tags/query posts

    Query_posts can be used to control which posts show up in The Loop. It accepts a variety of parameters in the same format as used in your URL. (e.g. p=4 to show only post of ID number 4)

    Why go through all the trouble of changing the query that was meticulously created from your given URL? You can customize the presentation of your blog entries by combining it with page logic (like the Conditional Tags) — all without changing any of the URLs.

    Common uses might be to:

    • Display only a single post or page on your homepage.
    • Show all posts from a particular time period.
    • Show the latest post (only) on the front page.
    • Change how posts are ordered.
    • Show posts from only one category.

    Usage

    Place a call to query_posts() in one of your Template files before The Loop begins. The wp_query object will generate a new SQL query using your parameters. When you do this, WordPress ignores the other parameters it receives via the URL (such as page number or category). If you want to preserve that information, you can use the variable $query_string in the call to query_posts().

    For example, to set the display order of the posts without affecting the rest of the query string, you could place the following before The Loop:

    query_posts($query_string . “&order=ASC”)

    When using query_posts in this way, the quoted portion of the argument must begin with an ampersand (&).

    Examples

    Exclude Categories From Your Home Page

    Placing this code in your index.php file will cause your home page to display posts from all categories except category ID 3.

    <?php
       if (is_home()) {
          query_posts("cat=-3");
       }
    ?>

    You can also add some more categories to the exclude-list(tested with WP 2.1.2):

    <?php
       if (is_home()) {
          query_posts("cat=-1,-2,-3");
       }
    ?>

    Retrieve a Particular Post

    To retrieve a particular post, you could use the following:

    <?php
    // retrieve one post with an ID of 5
    query_posts('p=5');
    ?>

    If you want to use the Read More functionality with this query, you will need to set the global $more variable to 0.

    <?php
    // retrieve one post with an ID of 5
    query_posts('p=5');
    
    global $more;
    // set $more to 0 in order to only get the first part of the post
    $more = 0; 
    
    // the Loop
    while (have_posts()) : the_post();
      // the content of the post
      the_content('Read the full post »');
    endwhile;
    ?>

    Retrieve a Particular Page

    To retrieve a particular page, you could use the following:

    <?php
    query_posts('page_id=7');      //retrieves page 7 only
    ?>

    or

    <?php
    query_posts('pagename=about'); //retrieves the about page only
    ?>

    For child pages, the slug of the parent and the child is required, separated by a slash. For example:

    <?php
    query_posts('pagename=parent/child'); // retrieve the child page of a parent
    ?>

    Passing variables to query_posts

    You can pass a variable to the query with two methods, depending on your needs. As with other examples, place these above your Loop:

    Example 1

    In this example, we concatenate the query before running it. First assign the variable, then concatenate and then run it. Here we’re pulling in a category variable from elsewhere.

     <?php
     $categoryvariable=$cat; // assign the variable as current category
     $query= 'cat=' . $categoryvariable. '&orderby=date&order=ASC'; // concatenate the query
     query_posts($query); // run the query
     ?>

    Example 2

    In this next example, the double ” quotes ” tell PHP to treat the enclosed as an expression. For this example, we are getting the current month and the current year, and telling query posts to bring us the posts for the current month/year, and in this case, listing in ascending so we get oldest post at top of page.

    <?php $current_month = date('m'); ?>
    <?php $current_year = date('Y'); ?>
    
    <?php query_posts("cat=22&year=$current_year&monthnum=$current_month&order=ASC"); ?>
    <!-- put your loop here -->

    Example 3

    This example explains how to generate a complete list of posts, dealing with pagination. We can use the default $query_string telling query posts to bring us a full posts listing. We can also modify the posts_per_page query argument from -1 to the number of posts you want to show on each page; in this last case, you’ll probably want to use posts_nav_link() to navigate the generated archive. .

    <?php
    query_posts($query_string.'posts_per_page=-1');
    while(have_posts()) { the_post();
    <!-- put your loop here -->
    }
    ?>

    Parameters

    This is not an exhaustive list yet. It is meant to show some of the more common things possible with setting your own queries.

    Category Parameters

    Show posts only belonging to certain categories.

    • cat
    • category_name

    Show One Category by ID

    Display posts from only one category ID:

    query_posts('cat=4');

    Show One Category by Name

    Display posts from only one category by name:

    query_posts('category_name=Staff Home');

    Show Several Categories by ID

    Display posts from several specific category IDs:

    query_posts('cat=2,6,17,38');

    Exclude Posts Belonging to Only One Category

    Show all posts except those from a category by prefixing its ID with a ‘-’ (minus) sign.

    query_posts('cat=-3');

    This excludes all the posts that belong only to category 3. There is a proviso however: it will exclude all the posts that belong only to category 3. If a post belongs to another category as well, it will still be picked up.

    Tag Parameters

    Show posts associated with certain tags.

    • tag

    Fetch posts for one tag

    query_posts('tag=cooking');

    Fetch posts that have either of these tags

    query_posts('tag=bread,baking');

    Fetch posts that have all three of these tags:

    query_posts('tag=bread+baking+recipe');

    Also see Ryan’s discussion of Tag intersections and unions.

    Author Parameters

    You can also restrict the posts by author.

    • author_name=Harriet
    • author=3

    author_name operates on the user_nicename field, whilst author operates on the author id.

    Post & Page Parameters

    Retrieve a single post or page.

    • p=1 - use the post ID to show the first post
    • name=first-post - use the Post Slug to show the first post
    • page_id=7
    • pagename=about
    • showposts=1 (you can also use showposts=3, or any number to display a limited number of posts

    As a consequence of the Template Hierarchy, home.php executes first. This means that you can write a home.php which calls query_posts() to retrieve a particular page and set that to be your front page. Without any plugins or hacks, you have got a mechanism to run, show and maintain a non-bloggy front page.

    More useful perhaps would be to take advantage of WP’s Page functionality and use that for your front page. You could set your “about page” to be the entry point or maybe your site’s colophon. You might even do something a bit more dynamic and set a custom page that shows a list of the latest comments, posts, categories and archives. See the example below.

    Time Parameters

    Retrieve posts belonging to a certain time period.

    • hour=
    • minute=
    • second=
    • day= - day of the month; shows all posts made, for example on the 15th.
    • monthnum=
    • year=

    Page Parameters

    • paged=2 - show the posts that would normally show up just on page 2 when using the “Older Entries” link.
    • posts_per_page=10 - number of posts to show per page; a value of -1 will show all posts.
    • order=ASC - show posts in chronological order, DESC to show in reverse order (the default)

    Offset Parameter

    You can displace or pass over one or more initial posts which would normally be collected by your query through the use of the offset parameter.

    The following will display the 5 posts which follow the most recent (1):

    query_posts('showposts=5&offset=1');

    Orderby Parameters

    Sort retrieved posts by this field.

    • orderby=author
    • orderby=date
    • orderby=category
    • orderby=title
    • orderby=modified
    • orderby=modified
    • orderby=menu_order
    • orderby=parent
    • orderby=ID
    • orderby=rand

    Also consider order parameter of “ASC” or “DESC”

    Combining Parameters

    You may have noticed from some of the examples above that you combine parameters with an ampersand (&), like so:

    query_posts('cat=3&year=2004');

    Posts for category 13, for the current month on the main page:

    if (is_home()) {
    query_posts($query_string . '&cat=13&monthnum=' . date('n',current_time('timestamp')));
    }

    At 2.3 this combination will return posts belong to both Category 1 AND 3, showing just two (2) posts, in descending order by the title:

     query_posts(array('category__and'=>array(1,3),'showposts'=>2,'orderby'=>title,'order'=>DESC));

    In 2.3 and 2.5 one would expect the following to return all posts that belong to category 1 and is tagged “apples”

    query_posts('cat=1&tag=apples');

    A bug prevents this from happening. See Ticket #5433. A workaround is to search for several tags using +

    query_posts('cat=1&tag=apples+apples');

    This will yield the expected results of the previous query. Note that using ‘cat=1&tag=apples+oranges’ yields expected results.

    Resources

    Comments are closed.

    Rudy Cahayadi is Digg proof thanks to caching by WP Super Cache!