Skip to content

query_posts and get_posts

março 27, 2010
Fonte: http://www.shibashake.com/wordpress-theme/wordpress-query_posts-and-get_posts
WordPress query_posts and get_posts
//
//

The WordPress query_posts command allows you to query the WordPress wp_posts database and retrieve post objects (e.g. posts, pages, attachments) based on their attributes.

query_posts is used throughout the WordPress administration system, but it is most prominent in the WordPress Loop and underlies all of the WordPress Loop commands, e.g. the_post or the_title.

get_posts is similar to query_posts and is also used to query the wp_posts database. You will note however, that the argument list it uses is slightly different compared to query_posts, therefore make sure to refer to the WordPress codex to ensure that you are using the right argument names for each of these commands.

Both query_posts and get_posts are based on the WP_Query object. However, query_posts creates a global WP_Query object that is stored in the $wp_query global variable, whereas get_posts creates a local WP_Query object that only exists within the function.

The global $wp_query variable is later used by multiple functions within the WordPress Loop. That is why it is important NOT to use query_posts within an existing WordPress Loop because it will replace the existing Loop object (contained in $wp_query) with a new WP_Query object.

query_posts is most useful when you are writing a plugin, and want to display a list of post objects within a WordPress administration menu. In the administration area, there is no Loop to worry about.

When you are operating outside of the WordPress administration area (i.e. WordPress Dashboard), it is best to use the get_posts command so that you do not inadvertently corrupt your WordPress Loop.

Incidentally, if you want to use query_posts type attributes within a WordPress Loop, then you can just create your own local WP_Query object as follows –

<?php
    $tmp_query = new WP_Query;
    return $tmp_query->query($atts);
?>

$atts should contain an attribute array similar to what you would use in the query_posts function. Here are the list of parameters for query_posts.

Here is another example –

<?php
    $tmp_query = new WP_Query;
    $tmp_result = $tmp_query->query('category_name=aciform');
?>
Anúncios
No comments yet

Deixe um comentário

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

%d blogueiros gostam disto: