Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |not checked

Usando WP_Query en WordPress

WP_Query es una de las clases más importantes dentro de WordPress si es que te dedicas a crear temas o necesitas modificar un tema. No hay prácticamente manera de que realices una consulta a tu base de datos personalizada sin WP_Query.

Introducción:

¿Cómo abarcaremos este tema? Bueno primero veremos como utilizar la clase WP_Query con un ejemplo y luego veremos los diferentes argumentos que le podemos pasar, WP_Query posee una gran cantidad de métodos también así que no será posible ponerlos en este post, tal vez veamos un par de hecho ya vimos algunos cuando vimos el loop de WordPress aunque no nos dimos cuenta.

Utilizando WP_Query.

WP_Query es el equivalente casi a hacer una consulta a nuestra base de datos, tal como decíamos antes, veamos el siguiente ejemplo en el cual si observa bien vemos que con los argumentos estamos filtrando que categorías queremos mostrar y cuantos elementos queremos mostrar en este caso -1 mostrara todos los elementos de esa categoría.

get_header();

$args = array( 'category_name' => 'postres','posts_per_page' => -1  );
$myposts = new WP_Query($args);

if ($myposts->have_posts() ) {

	// Load posts loop.
	while ( $myposts->have_posts() ) {
		$myposts->the_post();?>
		<a href="<?php the_permalink();?>">
		<h1><?php the_title();?></h1>
		</a>
		<?php the_content();
	}
}
else{
	echo "no post to be showed";
}

if ( have_posts() ) {

	// Load posts loop.
	while ( have_posts() ) {
		the_post();?>
		<a href="<?php the_permalink();?>">
		<h1><?php the_title();?></h1>
		</a>
		<?php the_content();
	}
}
else{
	echo "no post to be showed";
}
get_footer();

¿Qué pasa si no le paso argumentos? Pues nos basta con solo hacer la prueba ¿no?, Tomare el ejemplo anterior y borraré el loop que no está usando WP_Query y esto entre comillas porque realmente lo está usando internamente veremos como más adelante.

get_header();


$myposts = new WP_Query();

if ($myposts->have_posts() ) {

	// Load posts loop.
	while ( $myposts->have_posts() ) {
		$myposts->the_post();?>
		<a href="<?php the_permalink();?>">
		<h1><?php the_title();?></h1>
		</a>
		<?php the_content();
	}
}
else{
	echo "no post to be showed";
}

get_footer();

En este caso mostrará «no post to be showed» porque no le hemos pasado argumentos.

¿Cómo se Utiliza la clase WP_Query cuando realizamos un loop sin nosotros usarla?.

¿Cómo puede funcionar esto? Bueno como dije antes se utiliza la clase WP_Query y la razón de porque no vemos una variable que llame a los métodos como por ejemplo have_posts() es porque este método es otro método que internamente llama $wp_query->have_posts() y así es como lo hace. La variable $wp_query es global y es un objeto WP_Query.

Función have_posts()

function have_posts() {
    global $wp_query;
    return $wp_query->have_posts();
}

Qué argumentos les puedo pasar a WP_Query

Como ya sabe pasamos un parametro $arg a WP_Query antes de usarlo, los valores que podemos tener dentro de $args son los siguientes.

  • author (int) – use author id.
  • author_name (string) – use ‘user_nicename‘ – NOT name.
  • author__in (array) – use author id (available since version 3.7).
  • author__not_in (array) – use author id (available since version 3.7).
  • cat (int) – use category id.
  • category_name (string) – use category slug.
  • category__and (array) – use category id.
  • category__in (array) – use category id.
  • category__not_in (array) – use category id.
  • 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.
  • {tax} (string) – use taxonomy slug. (Deprecated since version 3.1 in favor of ‘tax_query‘).
  • tax_query (array) – use taxonomy parameters (available since version 3.1).
    • relation (string) – The logical relationship between each inner taxonomy array when there is more than one. Possible values are ‘AND’, ‘OR’. Do not use with a single inner taxonomy array.
      • taxonomy (string) – Taxonomy.
      • field (string) – Select taxonomy term by. Possible values are ‘term_id’, ‘name’, ‘slug’ or ‘term_taxonomy_id’. Default value is ‘term_id’.
      • terms (int/string/array) – Taxonomy term(s).
      • include_children (boolean) – Whether or not to include children for hierarchical taxonomies. Defaults to true.
      • operator (string) – Operator to test. Possible values are ‘IN’, ‘NOT IN’, ‘AND’, ‘EXISTS’ and ‘NOT EXISTS’. Default value is ‘IN’.
  • s (string) – Search keyword
  • 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 to return only child pages. Set to 0 to return only top-level entries.
  • post_parent__in (array) – use post ids. Specify posts whose parent is in an array. (available since version 3.6)
  • post_parent__not_in (array) – use post ids. Specify posts whose parent is not in an array. (available since version 3.6)
  • post__in (array) – use post ids. Specify posts to retrieve. ATTENTION If you use sticky posts, they will be included (prepended!) in the posts you retrieve whether you want it or not. To suppress this behaviour use ignore_sticky_posts.
  • post__not_in (array) – use post ids. Specify post NOT to retrieve.
  • post_name__in (array) – use post slugs. Specify posts to retrieve. (Will be available in version 4.4)
  • post_type (string / array) – use post types. Retrieves posts by post types, default value is ‘post‘. If ‘tax_query‘ is set for a query, the default value becomes ‘any‘;
    • post‘ – a post.
    • page‘ – a page.
    • revision‘ – a revision.
    • attachment‘ – an attachment. Whilst the default WP_Query post_status is ‘publish’, attachments have a default post_status of ‘inherit’. This means no attachments will be returned unless you also explicitly set post_status to ‘inherit’ or ‘any’. See Status parameters section below.
    • nav_menu_item‘ – a navigation menu item
    • any‘ – retrieves any type except revisions and types with ‘exclude_from_search’ set to true.
    • ** Custom Post Types (e.g. movies)
  • post_status (string / array) – use post status. Retrieves posts by post status. Default value is ‘publish‘, but if the user is logged in, ‘private‘ is added. Public custom post statuses are also included by default. And if the query is run in an admin context (administration area or AJAX call), protected statuses are added too. By default protected statuses are ‘future‘, ‘draft‘ and ‘pending‘.
    • 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 (available since version 2.9).
    • any‘ – retrieves any status except for ‘inherit’, ‘trash’ and ‘auto-draft’. Custom post statuses with ‘exclude_from_search’ set to true are also excluded.

–WORK IN PROGRESS–

Category: wordpress
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category