如果我的搜索在标题、内容或摘录中包含单词,如何过滤帖子中的搜索?

时间:2017-11-16 作者:Jordi Vicens

我正在尝试过滤一个搜索,我想知道一个词是否在标题、内容或摘录中,但运气不佳,最后我被绊倒了。

$args = array(
            \'post_type\' => \'post\',
            \'posts_per_page\' => \'-1\',
            \'search_prod_title\' => $_POST[\'wordToSearch\'],
            \'post_status\' => \'publish\',
            \'orderby\'     => \'title\',
            \'order\'       => \'ASC\'
        );

    add_filter( \'posts_where\', \'title_filter\', 10, 2 );
    add_filter( \'posts_where\', \'content_filter\', 10, 2 );
    add_filter( \'posts_where\', \'excerpt_filter\', 10, 2 );
    $posts = new WP_Query($args);
    remove_filter( \'posts_where\', \'title_filter\', 10, 2 );
    remove_filter( \'posts_where\', \'content_filter\', 10, 2 );
    remove_filter( \'posts_where\', \'excerpt_filter\', 10, 2 );
我的过滤函数是:

    function title_filter( $where, &$wp_query )
    {
        global $wpdb;
        if ( $search_term = $wp_query->get( \'search_prod_title\' ) ) {
            $where .= \' AND \' . $wpdb->posts . \'.post_title LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\'\';
        }
        return $where;
    }

    function content_filter( $where, &$wp_query )
    {
        global $wpdb;
        if ( $search_term = $wp_query->get( \'search_prod_content\' ) ) {
            $where .= \' AND \' . $wpdb->posts . \'.post_content LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\'\';
        }
        return $where;
    }

    function excerpt_filter( $where, &$wp_query )
    {
        global $wpdb;
        if ( $search_term = $wp_query->get( \'search_prod_excerpt\' ) ) {
            $where .= \' AND \' . $wpdb->posts . \'.post_excerpt LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\'\';
        }
        return $where;
    }
关键是,第一个过滤器功能工作正常,因此我可以按标题搜索,结果很好,但其余过滤器的结果错误或不工作。

1 个回复
SO网友:Jordi Vicens

好吧,无论是谁遇到了同样的问题,我都找到了解决办法:

我已更改过滤器,现在看起来像这样:

add_filter( \'posts_where\', \'general_filter\', 10, 2 );
$posts = new WP_Query($args);
remove_filter( \'posts_where\', \'general_filter\', 10, 2 );
以及函数。。。

function general_filter( $where, &$wp_query )
{
    global $wpdb;
    if ( $search_term = $wp_query->get( \'search_prod_title\' ) ) {
        $where .= \' AND (\' . $wpdb->posts . \'.post_title LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\' OR \' . $wpdb->posts . \' .post_excerpt LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\' OR \' . $wpdb->posts . \' .post_content LIKE \\\'%\' . esc_sql( like_escape( $search_term ) ) . \'%\\\')\';
    }
    return $where;
}
错误基本上是整个查询都错了,所以在调试变量时$where 我发现了错误并修复了它。希望这能帮助别人。

结束

相关推荐

Pre_Get_Posts有时以随机顺序显示帖子

我正在使用以下过滤器,以便将类别模板上显示的帖子数量从10个增加到30个(我想为网站的其余部分保留10个)// Modify number of results shown function modify_query_amount_shown($query){ if ($query->is_category) { $query->set(\'posts_per_page\', 30); $query->set(\'o