WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Difference between revisions of "Function Reference/query posts"

(Undo revision 100578 by Theryancollier (Talk))
(Custom Field Parameters: (correct multiple meta query example))
Line 670: Line 670:
 
$args = array(
 
$args = array(
 
'post_type' => 'product',
 
'post_type' => 'product',
'meta_query' =>
+
'meta_query' => array(
 
array(
 
array(
 
'key' => 'color',
 
'key' => 'color',
Line 682: Line 682:
 
'compare' => 'BETWEEN'
 
'compare' => 'BETWEEN'
 
)
 
)
  +
)
 
)
 
)
 
query_posts( $args );
 
query_posts( $args );

Revision as of 14:24, 17 February 2011

Description

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 the 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 on your homepage (a single Page can be done via Settings -> Reading).
  • 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.
  • Exclude one or more categories.

Important Notes

The query_posts() function is intended to be used to modify the main page loop only. It is not intended as a means to create secondary loops on the page. If you want to create separate Loops outside of the main one, you should use get_posts() instead. Use of query_posts() on loops other than the main one can result in your main loop becoming incorrect and possibly displaying things that you were not expecting.

The query_posts() function overrides and replaces the main query for the page. To save your sanity, do not use it for any other purpose.

The query_posts() function creates a new WP_Query object and assign it to global wp_query variable. The get_posts() function creates a new WP_Query object without overriding anything in the global area.

Usage

<?php

//The Query
query_posts( $args );

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

//Reset Query
wp_reset_query();

?>

Usage Note

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 $query_string global variable 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:

global $query_string;
query_posts( $query_string . "&order=ASC" );

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

Or alternatively, when adding parameter with multiple values, which must be in an array:

global $query_string;
parse_str( $query_string, $args );
$args[post_type] = array( 'post', 'video' );
query_posts( $args );

Or alternatively, you can merge the original query array into your parameter array:

global $wp_query;
$args = array_merge( $wp_query->query, array( 'post_type' => 'product' ) );
query_posts( $args );

Parameters

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

Author Parameters

Show posts associated with certain author.

  • author (int) - use author id.
  • author_name (string) - use 'user_nicename' (NOT name).

Show Posts for one Author

Display posts by author, using author id:

query_posts( 'author=123' );

Display posts by author, using author 'user_nicename':

query_posts( 'author_name=rami' );

Show Posts From Several Authors

Display posts from several specific authors:

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

Exclude Posts Belonging to an Author

Display all posts except those from an author by prefixing its id with a '-' (minus) sign:

query_posts( 'author=-12,-34,-56' );

Category Parameters

Show posts associated with certain categories.

  • cat (int) - use category id.
  • category_name (string) - use category slug (NOT name).
  • category__and (array) - use category id.
  • category__in (array) - use category id.
  • category__not_in (array) - use category id.

Show Posts for One Category

Display posts that have this category (and any children of that category), using category id:

query_posts( 'cat=4' );

Display posts that have this category (and any children of that category), using category slug:

query_posts( 'category_name=staff' );

Show Posts From Several Categories

Display posts that have these categories, using category id:

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

Display posts that have these categories, using category slug (not possible with wp3.0):

query_posts( 'category_name=staff,news' );

Exclude Posts Belonging to Category

Display all posts except those from a category by prefixing its id with a '-' (minus) sign.

query_posts( 'cat=-12,-34,-56' );

Multiple Category Handling

Display posts that are in multiple categories. This shows posts that are in both categories 2 and 6:

query_posts( array( 'category__and' => array( 2, 6 ) ) );

To display posts from either category 2 OR 6, you could use cat as mentioned above, or by using category__in (note this does not show posts from any children of these categories):

query_posts( array( 'category__in' => array( 2, 6 ) ) );

You can also exclude multiple categories this way:

query_posts( array( 'category__not_in' => array( 2, 6 ) ) );

Tag Parameters

Show posts associated with certain tags.

  • tag (string) - use tag slug.
  • tag_id (int) - use tag id.
  • tag__and (array) - use tag ids.
  • tag__in (array) - use tag ids.
  • tag__not_in (array) - use tag ids.
  • tag_slug__and (array) - use tag slugs.
  • tag_slug__in (array) - use tag slugs.

Show Posts for One Tag

Display posts that have this tag, using tag slug:

query_posts( 'tag=cooking' );

Display posts that have this tag, using tag id:

query_posts( 'tag_id=13' );

Show Posts From Several Tags

Display posts that have "either" of these tags:

query_posts( 'tag=bread,baking' );

Display posts that have "all" of these tags:

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

Multiple Tag Handling

Display posts that are tagged with both tag id 37 and tag id 47:

query_posts( array( 'tag__and' => array( 37, 47 ) ) );

To display posts from either tag id 37 or 47, you could use tag as mentioned above, or explicitly specify by using tag__in:

query_posts( array( 'tag__in' => array( 37, 47 ) ) );

Display posts that do not have any of the two tag ids 37 and 47:

query_posts( array( 'tag__not_in' => array( 37, 47 ) ) );

The tag_slug__in and tag_slug__and behave much the same, except match against the tag's slug.

Taxonomy Parameters

Show posts associated with certain taxonomy.

  • {tax} (string) - use taxonomy slug. Deprecated as of Version 3.1 in favor of 'tax_query'.
  • tax_query (array) - use taxonomy parameters (available with Version 3.1).
    • taxonomy (string) - Taxonomy.
    • field (string) - Select taxonomy term by ('id' or 'slug')
    • terms (int/string/array) - Taxonomy term(s).
    • operator (string) - Operator to test. Possible values are 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.

Simple Taxonomy Query:

Display posts tagged with 'bob', under 'people' custom taxonomy:

query_posts( array( 'people' => 'bob' ) );

Display posts tagged with 'bob', under 'people' custom taxonomy, using 'tax_query':

$args = array(
	'tax_query' => array(
		array(
			'taxonomy' => 'people',
			'field' => 'slug',
			'terms' => 'bob'
		)
	)
);
query_posts( $args );

Multiple Taxonomy Handling:

Display posts from several custom taxonomies:

query_posts( array( 'people' => 'bob', 'language' => 'english' ) );

Display posts from several custom taxonomies, using 'tax_query':

$args = array(
	'tax_query' => array(
		'relation' => 'AND',
		array(
			'taxonomy' => 'movie_janner',
			'field' => 'slug',
			'terms' => array( 'action', 'commedy' ),
		),
		array(
			'taxonomy' => 'actor',
			'field' => 'id',
			'terms' => array( 103, 115, 206 ),
			'operator' => 'NOT IN',
		)
	)
)
query_posts( $args );

Display posts that are in the 'quotes' category OR have the 'quote' format:

$args = array(
	'tax_query' => array(
		'relation' => 'OR',
		array(
			'taxonomy' => 'category',
			'field' => 'slug',
			'terms' => array( 'quotes' ),
		),
		array(
			'taxonomy' => 'post-format',
			'field' => 'slug',
			'terms' => array( 'post-format-quote' )
		)
	)
)
query_posts( $args );

Post & Page Parameters

Show posts associated with posts and pages.

  • p (int) - use post id.
  • name (string) - use post slug.
  • page_id (int) - use page id.
  • pagename (string) - use page slug.
  • post_parent (int) - use page id. Return just the child Pages.
  • post__in (array) - use post ids. Specify posts to retrieve.
  • post__not_in (array) - use post ids. Specify post NOT to retrieve.

Show Post/Page by ID

Display post by his ID:

query_posts( 'p=7' );

Display page by his ID:

query_posts( 'page=7' );

Show Post/Page by Slug

Display post by his slug:

query_posts( 'name=about-my-life' );

Display page by his slug:

query_posts( 'pagename=contact' );

Show Child Posts/Pages

Display child page using the slug of the parent and the child page, separated by a slash (e.g. 'parent_slug/child_slug'):

query_posts( 'pagename=contact_us/canada' );

Display child pages using parent page ID:

query_posts( 'post_parent=93' );

Multiple Posts/Pages Handling

Display only the specify posts:

query_posts( array( 'post__in' => array( 2, 5, 12, 14, 20 ) ) );

Display all posts but NOT the specify ones:

query_posts( array( 'post__not_in' => array( 2, 5, 12, 14, 20 ) ) );

Note: you cannot combine 'post__in' and 'post__not_in' in the same query.

Type & Status Parameters

Show posts associated with certain type or status.

  • post_type (string / array) - use post types. Retrieves posts by Post Types, default value is 'post';
    • 'post'
    • 'page'
    • 'revision'
    • 'attachment'
    • 'any' - retrieves any type except revisions
    • Custom Post Types (e.g. movies)
  • post_status (string / array) - use post status. Retrieves posts by Post Status, default value is 'publish';
    • 'publish' - a published post or page
    • 'pending' - post is pending review
    • 'draft' - a post in draft status
    • 'auto-draft' - a newly created post, with no content
    • 'future' - a post to publish in the future
    • 'private' - not visible to users who are not logged in
    • 'inherit' - a revision. see get_children.
    • 'trash' - post is in trashbin. added with Version 2.9.

Show Post by Type

Display only pages:

query_posts( 'post_type=page' );

Display 'any' post type (retrieves any type except revisions):

query_posts( 'post_type=any' );

Display multiple post types, including custom post types:

query_posts( array( 'post_type' => array( 'post', 'page', 'movie', 'book' ) ) );

Show Post by Status

Display only drafts:

query_posts( 'post_status=draft' );

Display multiple post status:

query_posts( array( 'post_status' => array( 'pending', 'draft', 'future' ) ) );

Pagination Parameters

  • showposts (int) - number of post to show per page. Deprecated as of Version 2.1 in favor of 'posts_per_page'.
  • posts_per_page (int) - number of post to show per page (available with Version 2.1). Use 'posts_per_page'=>-1 to show all posts. Note if the query is in a feed, wordpress overwrites this parameter with the stored 'posts_per_rss' option. To reimpose the limit, try using the 'post_limits' filter.
  • nopaging (bool) - show all posts or use pagination. Default value is 'false', use paging.
  • paged (int) - number of page. Show the posts that would normally show up just on page X when using the "Older Entries" link.

Show x Posts per page

Display 3 posts per page:

query_posts( 'posts_per_page=3' );

Show All Post

Display all posts in one page:

query_posts( 'posts_per_page=-1' );

Display all posts by disabling pagination:

query_posts( 'nopaging=true' );

Show Posts from page x

Display posts from page number 6:

query_posts( 'paged=6' );

Show Posts from Current Page

Display posts from current page:

query_posts( 'paged=' . get_query_var( 'page' ) );

Pagination Note: You should set get_query_var( 'page' ); if you want your query to work with pagination. Since Wordpress 3.0.2, you do get_query_var( 'page' ) instead of get_query_var( 'paged' ). The pagination parameter 'paged' for query_posts() remains the same.

Offset Parameter

  • offset (int) - number of post to displace or pass over.

Pass over 3 Posts

Display posts from the 4th one:

query_posts( 'offset=3' ) );

Show 5 Posts starting from the second one

Display 5 posts per page which follow the most recent (1):

query_posts( array( 'posts_per_page' => 5, 'offset' => 1 ) );

Order & Orderby Parameters

Sort retrieved posts.

  • order (string) - Designates the ascending or descending order of the 'orderby' parameter.
    • 'ASC' - ascending order from lowest to highest values (1, 2, 3; a, b, c).
    • 'DESC' - descending order from highest to lowest values (3, 2, 1; c, b, a).
  • orderby (string) - Sort retrieved posts by:
    • 'none' - No order (available with Version 2.8).
    • 'id' - Order by post id.
    • 'author' - Order by author.
    • 'title' - Order by title.
    • 'date' - Order by date. (default, if not set to none)
    • 'modified' - Order by last modified date.
    • 'parent' - Order by post/page parent id.
    • 'rand' - Random order.
    • 'comment_count' - Order by number of comments (available with Version 2.9).
    • 'menu_order' - Order by Page Order. Used most often for Pages (Order field in the Edit Page Attributes box) and for attachments (the integer fields in the Insert / Upload Media Gallery dialog), but could be used for any post type with distinct 'menu_order' values (they all default to 0).
    • 'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note also that the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect).
    • 'meta_value_num' - Order by numeric meta value (available with Version 2.8). Also note that a 'meta_key=keyname' must also be present in the query. This value allows for numerical sorting as noted above in 'meta_value'.

Show Posts sorted by Title, Descending order

Display posts sorted by post title in a descending order:

query_posts( 'orderby=title&order=DESC' );

Show Random Post

Display one random post:

query_posts( 'orderby=rand&posts_per_page=1' );

Show Popular Posts

Display posts ordered by comment count:

query_posts( 'orderby=comment_count' );

Show Products sorted by Price

Display posts with 'Product' type ordered by 'Price' custum field:

query_posts( array ( 'post_type' => 'product', 'orderby' => 'meta_value', 'meta_key' => 'price' ) );

Note, that there can be more than one orderby value.

Display 'page' post type ordered by 'title' and 'menu_order'. (Separated with spaces to work properly.)

query_posts( 'post_type=page&orderby=title menu_order&order=ASC' );

Sticky Post Parameters

Show Sticky Posts or ignore them.

  • caller_get_posts (bool) - ignore sticky posts or not. Deprecated as of Version 3.1 in favor of 'ignore_sticky_posts'.
  • ignore_sticky_posts (bool) - ignore sticky posts or not. Default value is 0, don't ignore. Ignore/exclude sticky posts being included at the beginning of posts returned, but the sticky post will still be returned in the natural order of that list of posts returned.

Show Sticky Posts

Display just the first sticky post:

$sticky = get_option( 'sticky_posts' );
query_posts( 'p=' . $sticky[0] );

Display just the first sticky post, if none return the last post published:

$args = array(
	'posts_per_page' => 1,
	'post__in'  => get_option( 'sticky_posts' ),
	'ignore_sticky_posts' => 1
);
query_posts( $args );

Display just the first sticky post, if none return nothing:

$sticky = get_option( 'sticky_posts' );
$args = array(
	'posts_per_page' => 1,
	'post__in'  => $sticky,
	'ignore_sticky_posts' => 1
);
query_posts( $args );
if ( $sticky[0] ) {
	// insert here your stuff...
}

Don't Show Sticky Posts

Exclude all sticky posts from the query:

query_posts( array( 'post__not_in' => get_option( 'sticky_posts' ) ) );

Exclude sticky posts from a category. Return ALL posts within the category, but don't show sticky posts at the top. The 'sticky posts' will still show in their natural position (e.g. by date):

query_posts( 'ignore_sticky_posts=1&posts_per_page=3&cat=6' );

Exclude sticky posts from a category. Return posts within the category, but exclude sticky posts completely, and adhere to paging rules:

$paged = get_query_var( 'page' ) ? get_query_var( 'page' ) : 1;
$sticky = get_option( 'sticky_posts' );
$args = array(
	'cat' => 3,
	'ignore_sticky_posts' => 1,
	'post__not_in' => $sticky,
	'paged' => $paged
);
query_posts( $args );

Time Parameters

Show posts associated with a certain time period.

  • year (int) - 4 digit year (e.g. 2011).
  • monthnum (int) - Month number (from 1 to 12).
  • w (int) - Week of the year (from 0 to 53). Uses the MySQL WEEK command Mode=1.
  • day (int) - Day of the month (from 1 to 31).
  • hour (int) - Hour (from 0 to 23).
  • minute (int) - Minute (from 0 to 60).
  • second (int) - Second (0 to 60).

Returns posts for just the current date:

$today = getdate();
query_posts( 'year=' . $today["year"] . '&monthnum=' . $today["mon"] . '&day=' . $today["mday"] );

Returns posts for just the current week:

$week = date('W');
$year = date('Y');
query_posts( 'year=' . $year . '&w=' . $week );

Returns posts dated December 20:

query_posts( 'monthnum=12&day=20' );

Note: The queries above return posts for a specific date period in history, i.e. "Posts from X year, X month, X day". They are unable to fetch posts from a timespan relative to the present, so queries like "Posts from the last 30 days" or "Posts from the last year" are not possible with a basic query, and require use of the posts_where filter to be completed. The examples below use the posts_where filter, and should be modifyable for most time-relative queries.

Return posts for posts for March 1 to March 15, 2009:

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
	// posts for March 1 to March 15, 2010
	$where .= " AND post_date >= '2010-03-01' AND post_date < '2010-03-16'";
	return $where;
}
add_filter( 'posts_where', 'filter_where' );

query_posts( $query_string );

Return posts from the last 30 days:

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
	// posts in the last 30 days
	$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
	return $where;
}
add_filter( 'posts_where', 'filter_where' );

query_posts( $query_string );

Return posts 30 to 60 days old

// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
	// posts  30 to 60 days old
	$where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-30 days')) . "'";
	return $where;
}
add_filter( 'posts_where', 'filter_where' );

query_posts( $query_string );

Custom Field Parameters

Show posts associated with a certain custom field.

  • meta_key (string) - Custom field key. Deprecated as of Version 3.1 in favor of 'meta_query'.
  • meta_value (string) - Custom field value. Deprecated as of Version 3.1 in favor of 'meta_query'.
  • meta_compare (string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or '<='. Default value is '='. Deprecated as of Version 3.1 in favor of 'meta_query'.
  • meta_query (array) - Custom field parameters (available with Version 3.1).
    • key (string) - Custom field key.
    • value (string) - Custom field value.
    • compare (string) - Operator to test. Possible values are 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
    • type (string) - Custom field type. Possible values are 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. Default value is 'CHAR'.

Simple Custom Field Query:

Display posts where the custom field key is 'color', regardless of the custom field value:

query_posts( 'meta_key=color' );

Display posts where the custom field value is 'blue', regardless of the custom field key:

query_posts( 'meta_value=blue' );

Display Page where the custom field value is 'blue', regardless of the custom field key:

query_posts( 'meta_value=blue&post_type=page' );

Display posts where the custom field key is 'color' and the custom field value is 'blue':

query_posts( array( 'meta_key' => 'color', 'meta_value' => 'blue' ) );

Display posts where the custom field key is 'color' and the custom field value IS NOT 'blue':

query_posts( array( 'meta_key' => 'color', 'meta_value' => 'blue', 'meta_compare' => '!=' ) );

Display 'product'(s) where the custom field key is 'price' and the custom field value that is LESS THAN OR EQUAL TO 22. Note the value 99 will be considered greater than 100 as the data is stored as 'strings', not 'numbers'.

query_posts( array( 'meta_key' => 'price', 'meta_value' => '22', 'meta_compare' => '<=', 'post_type' => 'product' ) );

Display posts with a custom field value of zero (0), regardless of the custom field key:

query_posts( array ( 'meta_value' => '_wp_zero_value' ) );

Multiple Custom Field Handling:

Display posts from several custom field:

$args = array(
	'post_type' => 'product',
	'meta_query' => array(
		array(
			'key' => 'color',
			'value' => 'blue',
			'compare' => 'NOT LIKE'
		),
		array(
			'key' => 'price',
			'value' => array( 20, 100 ),
			'type' => 'numeric',
			'compare' => 'BETWEEN'
		)

)

)
query_posts( $args );

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), 'posts_per_page' => 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.

Examples

Exclude Categories From Your Home Page

Placing this code in index.php file will cause the 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:

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' );

// set $more to 0 in order to only get the first part of the post
global $more;
$more = 0;

// the Loop
while (have_posts()) : the_post();
	the_content( 'Read the full post »' );
endwhile;
?>

All Posts in a Category

The "Blog pages show at most" parameter in Settings > Reading can influence your results. To overcome this, add the 'posts_per_page' parameter. For example:

query_posts( array ( 'category_name' => 'The Category Name', 'posts_per_page' => -1 ) );

This will returns ALL posts from the category.

Syndication Feeds

The "Syndication feeds show the most recent" or 'posts_per_rss' parameters in Settings > Reading will overwrite any 'posts_per_page' parameter in a query used in a feed.

To overcome use (for example in a a custom ics feed, where all matching posts are required), use the "posts_limit" filter as follows:

if ( isset ( $query->query_vars['feed'] ) and ( $query->query_vars['feed'] == 'ics' ) )
	add_filter( 'post_limits', 'no_limits_for_feed' );

function no_limits_for_feed( $limits ) {
	return '';
}

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.

$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 order so we get the oldest post at the top of the page.

$current_year = date('Y');
$current_month = date('m');

query_posts( "cat=22&year=$current_year&monthnum=$current_month&order=ASC" );

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.

query_posts( $query_string . '&posts_per_page=-1' );

Example 4

If you don't need to use the $query_string variable, another method exists that is more clear and readable, in some more complex cases. This method puts the parameters into an array. The same query as in Example 2 above could be done like this:

$args = array(
	'cat'      => 22,
	'year'     => $current_year,
	'monthnum' => $current_month,
	'order'    => 'ASC'
);
query_posts( $args );

As you can see, with this approach, every variable can be put on its own line, for easier reading.

Filters

  • posts_distinct - applied to the 'DISTINCTROW' clause to the query that returns the post array.
  • posts_groupby - applied to the 'GROUP BY' clause of the query that returns the post array.
  • posts_join - applied to the 'JOIN' clause of the query that returns the post array.
  • post_limits - applied to the 'LIMIT' clause of the query that returns the post array.
  • posts_orderby - applied to the 'ORDER BY' clause of the query that returns the post array.
  • posts_where - applied to the 'WHERE' clause of the query that returns the post array.
  • posts_request - applied to the entire SQL query that returns the post array, just prior to running the query.

Resources

Related

Articles

Code Documentation

  • Class: WP_Query - Detailed Overview of class WP_Query
  • Class: WP_Comment_Query - Class for comment-related queries
  • Class: WP_User_Query - Class for user-related queries
  • Object: $wpdb - Overview on the use of the $wpdb object
  • Function: get_query_var()
  • Function: query_posts() - Create additional custom query
  • Function: get_post() - Take an ID of an item and return the records in the database for that article
  • Function: get_posts() - A specialized function that returns an array of items
  • Function: get_pages() - A specialized function that returns an array of pages
  • Function: have posts() - a condition that determines whether the query returned an article
  • Function: the_post() - Used to automatically set the loop after a query
  • Function: rewind_posts() - Clears the current loop
  • Function: setup_postdata() - Sets the data for a single query result within a loop
  • Function: wp_reset_postdata() - Restores the previous query (usually after a loop within another loop)
  • Function: wp_reset_query()
  • Function: is_main_query() - Ensures that the query that is being changed is only the main query
  • Action Hook: pre_get_posts - Change WordPress queries before they are executed
  • Action Hook: the_post - Modify the post object after query
  • Filter Hook: found_posts - Changes the value of the object found_posts WP_Query
See also index of Function Reference and index of Template Tags.