Using WordPress ‘query_posts()’ PHP function

The query_posts() WordPress PHP function sets up The Loop with query parameters. This function overrides the main query and is not intended for use by plugins or themes due to its simplistic approach to modifying the main query. It’s recommended to use the ‘pre_get_posts’ action within WP_Query instead.

Usage

A generic example of how to use the function:

query_posts( array( 'category_name' => 'my-category-slug', 'posts_per_page' => -1 ) );

Parameters

  • $query (array|string) Required: Array or string of WP_Query arguments.

More information

See WordPress Developer Resources: query_posts()

Examples

Override the main query with all posts in a specific category

if ( is_category( 'category-slug' ) ) :
    query_posts( array( 'category_name' => 'my-category-slug', 'posts_per_page' => -1 ) );
endif;

Passing variables to query_posts using concatenation

// assign the variable as current category
$categoryvariable = $cat;

// concatenate the query
$args = 'cat=' . $categoryvariable . '&orderby=date&order=ASC';

// run the query
query_posts( $args );

Passing variables to query_posts using double quotes

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

Generate a complete list of posts, dealing with pagination

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts( array( 'posts_per_page' => 10, 'paged' => $paged ) );

Query posts with multiple categories and tags

query_posts( array(
    'category__and' => array( 1, 3 ),
    'tag__in' => array( 4, 5 ),
    'posts_per_page' => 5,
    'orderby' => 'date',
    'order' => 'DESC'
) );