Sử dụng pre_get_posts với WP_Query (ok)

https://qastack.vn/wordpress/52480/using-pre-get-posts-with-wp-query

Tôi đã đọc Stephen Harris câu trả lời tuyệt vời 's đến câu hỏi này liên quan đến việc sử dụng WP_query(), query_posts()pre_get_posts.

Ông nói "pre_get_posts là một bộ lọc, để thay đổi bất kỳ truy vấn nào . Nó thường được sử dụng để chỉ thay đổi 'truy vấn chính'."

Có thể sử dụng pre_get_postsđể chỉ lọc một truy vấn thứ cấp cụ thể được tạo bằng WP_Query? ví dụ.

$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();

Bất kỳ trợ giúp nhiều đánh giá cao.

Cách đơn giản nhất là thêm hành động ngay trước truy vấn và xóa nó ngay sau đó.

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();

CHỈNH SỬA

Một kỹ thuật khác bạn có thể sử dụng là đặt var truy vấn của riêng bạn và kiểm tra xem trong hook:

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

và trong mẫu:

// 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 );

Last updated