最简单的方法是在查询之前添加操作,然后在查询之后立即将其删除。
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();
编辑
您可以使用的另一种技术是设置自己的查询var并在一个钩子中检查它:
// 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' );
并在模板中:
// 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 );