在自定义帖子类型和带有类别的页面中搜索

时间:2020-10-14 作者:Rvervuurt

我有一个搜索字段,正在我的自定义帖子类型中搜索bwps 使用隐藏输入:

<form class="search-form form-inline" action="<?php echo site_url(\'/\'); ?>" method="get" role="search">
  <label class="sr-only"></label>
  <input class="searchInput" type="search" required="" placeholder="<?php _e(\'Search for event\', \'mhe\') ?>" name="s" value=""></input>
  <input type="hidden" name="post_type" value="bwps" />
  <button class="searchButton" type="submit"><span class="glyphicon glyphicon-search" aria-hidden="true"></span> <span class="searchButtonText"><?php _e(\'Search\', \'mhe\') ?></span></button>
</form>
但是,客户现在还希望在所有页面中搜索,但只搜索具有特定类别的页面。

如何进行此搜索表单搜索EVERYTHING 在自定义帖子类型中ONLY 具有特定类别的页面?这可能吗?

1 个回复
SO网友:Antti Koskinen

几个月前你可能已经解决了这个问题,但我这是我的2美分,因为我认为这是一个有趣的问题

我不认为标准的WP搜索查询可以用于搜索具有(帖子类型A)或(帖子类型B和类别C)的帖子。但是,您可以使用将自定义where子句传递给查询posts_where 筛选以处理此类情况。

我觉得这样应该行得通,

add_filter( \'posts_where\' , \'my_posts_where\', 10, 2 );
function my_posts_where( $where, $query ) {

    if ( is_admin() || ! is_search() || ! is_main_query() ) {
        return $where;
    }

    // check that requred $_GET parameters are set
    if ( ! empty( $_GET[\'post_type\'] ) || \'bwps\' !== $_GET[\'post_type\'] ) {
        return $where;
    }

    if ( empty( $_GET[\'s\'] ) ) {
        return $where;
    }

    // return custom where clause
    global $wpdb;
    $sql = "
        AND (
            {$wpdb->posts}.post_title LIKE \'%%%s%%\' OR
            {$wpdb->posts}.post_name LIKE \'%%%s%%\'
        )
        AND
            {$wpdb->posts}.post_status = \'publish\'
        AND
            (
                (
                    {$wpdb->posts}.post_type = \'bwps\'
                ) OR
                (
                    {$wpdb->posts}.post_type = \'page\'
                    AND
                    {$wpdb->posts}.ID IN (
                        SELECT {$wpdb->posts}.ID FROM {$wpdb->posts} AS p
                        INNER JOIN {$wpdb->term_relationships} AS tr ON (p.ID = tr.object_id)
                        INNER JOIN {$wpdb->term_taxonomy} AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
                        INNER JOIN {$wpdb->terms} AS t ON (t.term_id = tt.term_id)
                        WHERE
                            p.post_status = \'publish\'
                            AND t.term_id = %d
                            AND tt.taxonomy = \'category\'
                    )
                )
            )
    ";

    $search_phrase = \'%\' . $_GET[\'s\'] . \'%\';
    $term_id = 1;

    return $wpdb->prepare(
        $sql,
        $search_phrase,
        $search_phrase,
        $term_id
    );
}

相关推荐

nothing happen in search form

我想创建搜索表单,但当我搜索时什么都没有发生,这是代码:索引。php: <div class=\"tech-btm\"> <?php get_search_form();?> </div> 搜索表单:<form role=\"search\" method=\"get\" id=\"searchform\" action=\"<?php echo home_url(\'/\')?>\"> &