WordPress.org

Ready to get started?Download WordPress

Codex

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

pt-br:Referência de Funções/query posts&action=edit

Contents

Descrição

Dentre todas as formas de modificar a query principal do WordPress, query_posts() é a mais simples, mas não é a preferida, nem a mais eficiente. Ela ignora a query principal e a substitui por uma nova. Para retornar à query principal depois de uma chamada a query_posts(), use a função wp_reset_query() e ela será restaurada.

É muito preferível e recomendado que ao invés de query_posts() você use a action pre_get_posts, alterando a query principal - que você pode detectar checando com is_main_query.

Por exemplo: na página principal você normalmente verá 10 posts. Se quiser mostrar apenas 5 (e não se importar com a paginação), você pode usar query_posts() assim:

query_posts( 'posts_per_page=5' );

Abaixo você vê a mesma funcionalidade, mas usando pre_get_posts no arquivo functions.php:

function five_posts_on_homepage( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'posts_per_page', '5' );
    }
}
add_action( 'pre_get_posts', 'five_posts_on_homepage' );

Ressalvas

query_posts() é somente uma dentre várias maneiras de buscar informações no banco de dados e gerar uma lista de posts. Antes de se decidir por ela, tenha certeza que conhece as desvantagens.

Altera o loop principal

query_posts() foi criada para alterar o loop principal. Ela faz isso substituindo a query usada para gerar o conteúdo do loop principal. A cada vez que você usar query_posts(), as variáveis globais relacionadas aos posts e as Template Tags também serão alteradas - isso pode ou não ser o que resultado que você deseja.

Loops secundários

Para criar listas secundárias - por exemplo, uma lista de posts relacionados no rodapé ou uma lista de links na barra lateral - experimente criar uma nova instância da classe WP_Query, ou use get_posts().

Se você absolutamente necessita usar query_posts(), então certifique-se de chamar wp_reset_query() depois que usar os dados.

Paginação

A paginação não vai funcionar corretamente a menos que você use o argumento 'paged' da forma correta: adding the paged parameter

Queries SQL adicionais

If you use query_posts within a template page, WordPress will have already executed the database query and retrieved the records by the time it gets to your template page (that's how it knew which template page to serve up!). So when you over-ride the default query with query_posts(), you're essentially throwing away the default query and its results and re-executing another query against the database.

This is not necessarily a problem, especially if you're dealing with a smaller blog-based site. Developers of large sites with big databases and heavy visitor traffic may wish to consider alternatives, such as modifying the default request directly (before it's called). The request filter can be used to achieve exactly this.

The 'parse_query' and the 'pre_get_posts' filters are also available to modify the internal $query object that is used to generate the SQL to query the database.

Usage

<?php
// The Query
query_posts$args );

// The Loop
while ( have_posts() ) : the_post();
    echo 
'<li>';
    
the_title();
    echo 
'</li>';
endwhile;

// Reset Query
wp_reset_query();
?>
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).

Preserving Existing Query Parameters

If you want to preserve the original query parameter information that was used to generate the current query, and then add or over-ride some parameters, 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 parameter must begin with an ampersand (&).

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

global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'post_type' => 'product' ) );
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' ) );

The following returns all posts that belong to category 1 and are tagged "apples"

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

You can search for several tags using +

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

Parameters

Note: Parameter details can be found in the Parameter section of the WP_Query class article.

The examples below also work with the WP_Query object.

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 3.3.1):

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

Note: If the particular post is an attachment, you have to use attachment_id instead of p:

query_posts( 'attachment_id=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' => 'my-category-slug', 'posts_per_page' => -1 ) );

This will returns ALL posts from the category.

However, for subcategories (or child categories), 'The Category Name' doesn't always work. Rather use 'category-slug' instead. See Function_Reference/is_category.

if (is_category('category-slug')): 

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

endif; 

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', '__return_empty' );
}

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.

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

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

// run the query
query_posts( $args );

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 parameter 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.

Example 5

It is even possible to use the array style (Example 4) to query multiple taxonomies. Simply supply the taxonomy slug with a string of comma-separated values (each value being one term). In the example below, we will get all movie posts starring either Bruce Campbell or Chuck Norris.

$args = array(
	'post_type'=> 'movie',
	'actor'    => 'Bruce Campbell, Chuck Norris',
	'order'    => 'ASC'
);
query_posts( $args );

Change Log

Since: 1.5.0

Source File

query_posts() is located in wp-includes/query.php.

Resources

Related

Articles

Code Documentation

  • Class: WP_Query - Detailed Overview of class WP_Query
  • 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.