Usando pre_get_posts con WP_Query

22

Estaba leyendo la excelente respuesta de Stephen Harris a esta pregunta relacionada con el uso de WP_query() , query_posts() y pre_get_posts .

Dice "pre_get_posts es un filtro, para modificar cualquier consulta . Se usa con más frecuencia para alterar solo la 'consulta principal'."

¿Es posible usar pre_get_posts para filtrar solo una consulta secundaria específica creada con WP_Query ? por ejemplo.

$my_secondary_loop = new WP_Query(...);
if( $my_secondary_loop->have_posts() ):
    while( $my_secondary_loop->have_posts() ): $my_secondary_loop->the_post();
       //The secondary loop
    endwhile;
endif;
wp_reset_postdata();

Cualquier ayuda muy apreciada.

    
pregunta Ben Pearson 17.05.2012 - 21:59

2 respuestas

23

La forma más sencilla es agregar la acción justo antes de la consulta y eliminarlo inmediatamente después.

add_action('pre_get_posts', 'some_function_in_functionsphp');
$my_secondary_loop = new WP_Query(...);
remove_action('pre_get_posts', 'some_function_in_functionsphp');

if( $my_secondary_loop->have_posts() ):
    while( $my_secondary_loop->have_posts() ): $my_secondary_loop->the_post();
       //The secondary loop
    endwhile;
endif;
wp_reset_postdata();

EDIT

Otra técnica que puedes usar es establecer tu propia var de consulta y verificarla en un gancho:

// tell WordPress about our new query var
function wpse52480_query_vars( $query_vars ){
    $query_vars[] = 'my_special_query';
    return $query_vars;
}
add_filter( 'query_vars', 'wpse52480_query_vars' );

// check if our query var is set in any query
function wpse52480_pre_get_posts( $query ){
    if( isset( $query->query_vars['my_special_query'] ) )
        // do special stuff

    return $query;
}
add_action( 'pre_get_posts', 'wpse52480_pre_get_posts' );

y en la plantilla:

// set the query var (along with whatever others) to trigger the filter
$args = array(
    'my_special_query' => true
);
$my_secondary_loop = new WP_Query( $args );
    
respondido por el Milo 17.05.2012 - 22:10
4
  

pre_get_posts dispara para cada consulta de publicación:

     
  • get_posts ()
  •   
  • new WP_Query ()
  •   
  • Ese widget aleatorio de publicaciones recientes que tu cliente instaló sin que lo supieras.
  •   
  • Todo
  •   

- @nacin

Dicho esto, a menos que excluyas tu filtro, usa el condicional: is_main_query() , entonces tu filtro se activará en tu nuevo WP_Query.

Si solo quieres dirigirte a tu nuevo WP_Query específico, no hay forma de hacerlo.

    
respondido por el Chris_O 17.05.2012 - 22:11

Lea otras preguntas en las etiquetas