为WP_QUERY()注册自定义查询参数

时间:2012-10-16 作者:Andre

我写了一个插件,它可以在自己的数据库表中存储每个帖子(产品)的技术规格表。对于站点的搜索功能,我想向传递给的数组添加一个自定义参数WP_Query().我不知道在哪里注册这个自定义参数,以便插件尽快处理它WP_Query() 执行搜索。

插件中是否有一个钩子可以用来限制WP_Query() 到与给定规格匹配的特定集合?还是最终必须使用SQL构建整个查询?

请参见以下示例:“标准”-参数旁边有一个自定义参数_spec 我希望插件以某种方式解析它的值。

<?php

new WP_Query(
    array(

        \'s\' => \'some keyword\', //keyword criterion
        \'category\' => \'some category\', //taxonomy criterion

        \'_spec\' => \'year_min=1980;year_max=2010\', //custom criterion to be handled by the plugin

    )
);

?>

1 个回复
最合适的回答,由SO网友:Andre 整理而成

经过进一步研究,我想出了一个解决办法。鉴于以下情况WP_Query:

<?php

new WP_Query(
    array(

        \'s\' => \'some keyword\', //keyword criterion
        \'category\' => \'some category\', //taxonomy criterion

        \'_spec\' => \'some value\', //custom criterion to be handled by the plugin

    )
);

?>
可以使用pre_get_posts 结合posts_where:

<?php

add_action( \'pre_get_posts\', \'my_pre_get_posts\' ); //hook into the query before it is executed

$custom_where_string = \'\'; //used to save the generated where string between filter functions

function my_pre_get_posts( $query )
{
    global $custom_where_string;

    //if the custom parameter is used
    if(isset($query->query_vars[\'_spec\'])){

        //here you can parse the contents of $query->query_vars[\'_spec\'] to modify the query
        //even the first WHERE starts with AND, because WP adds a "WHERE 1=1" in front of every WHERE section
        $custom_where_string = \'AND ...\';

        //only if the custom parameter is used, hook into the generation of the query
        add_filter(\'posts_where\', \'my_posts_where\'));
    }
}

function my_posts_where( $where )
{
    global $custom_where_string;

    //append our custom where expression(s)
    $where .= $custom_where_string;

    //clean up to avoid unexpected things on other queries
    remove_filter(\'posts_where\', \'my_posts_where\'));
    $custom_where_string = \'\';

    return $where;
}


?>
附言:看看http://codex.wordpress.org/Class_Reference/WP_Query#Filters 用于操作SQL查询的其他部分(例如JOIN)

结束

相关推荐

使用新的WP-Query()从循环中过滤后期格式;

嗨,我目前正在为我的博客构建一个主题。下面的代码指向最新的帖子(特色帖子)。因为这将有一个不同的风格比所有其他职位。然而我想过滤掉帖子格式:链接使用我在循环中定义的WP查询,因为它给我带来了更多的灵活性。我该怎么做呢? <?php $featured = new WP_Query(); $featured->query(\'showposts=1\'); ?> <?php while ($featured->have_post