将条件添加到Wordpress中已存在的WP_Query中


Add conditions to existed WP_Query in Wordpress

我想添加一些过滤器来选择需要的帖子,比如:

function exclude_post($query) {
    if ($query->is_home) {
       // Do some PHP code
    }    
    return $query;
}
add_filter('pre_get_posts', 'exclude_post');

如何向已存在的WP_Query实例$query添加新条件?

如果您想用过滤器修改查询,您可以在函数中使用$query->set('post_type', 'post');,只需在函数中添加参数即可。

如果你想修改主循环,你可以使用这个:

global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'post_type' => 'product' ) );
query_posts( $args );
$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'people',
            'field' => 'slug',
            'terms' => 'bob'
        )
    )
);
$query = new WP_Query( $args );

来自codex的一个片段在这里查看更多wp查询

您想创建一个自定义的帖子列表,但又不想丢失当前的wp_query?简单,使用wp_reset_query()

$my_query = new WP_Query( $argument_array );
//... Do all you have to do with the query ... 
wp_reset_query(); // This will restore the original query.

作为wp_reset_query()的替代方案,并为您的查询提供更多控制,以下是对我有效的方法:

您可以使用array_push()将添加到$args数组中。然后,您只需创建一个新的WP_Query。当然,只有当您仍然有$args变量集时,这才会起作用。

在你的代码中,你可以写:

$new_arg = array('tax_query' => array(
                array(
                    'taxonomy' => get_query_var('taxonomy'),
                    'field'    => 'slug',
                    'terms'    => get_query_var('term'),
                ),
            )
);
array_push($args,$new_arg);
$query = new WP_Query( $args );

在上面的代码中,我只是使用array_push将一个新的数组元素添加到WP_QUERY正在使用的同一数组中。然后,我只是简单地将它传递回WP_QUERY。

我希望这能帮助到别人。