使用文本输入进行高级搜索,仅搜索一个类别

时间:2018-11-02 14:41:42

标签: php wordpress search

此目标是尽可能多地使用WordPress核心功能。

advanced.php-这是自定义搜索表单...

<form method="get" id="advanced-searchform" role="search" action="<?php echo esc_url( home_url( '/' ) ); ?>">

<input type="hidden" name="search" value="post">

<input id="search-case-study" class="search-case-study" type="text" value="" placeholder="Search..." name="s" />

<input type="submit" id="searchsubmit" value="Search" />

functions.php

// CASE STUDY SEARCH
function advanced_search_query($query) {

    if($query->is_search()) {
        // category terms search.
        $query->set('tax_query', array(
            array(
                'taxonomy' => 'case-study',
                'field' => 'slug'
            )
        ));
    }
    return $query;
}

add_action('pre_get_posts', 'advanced_search_query');
// END CASE STUDY SEARCH

我还使用以下方法将表单调用到页面中:

<?php get_template_part( 'advanced', 'searchform' ); ?>

表格正确地插入页面。

该表单包含我要使用的字段。

我只需要帮助在functions.php中创建查询。

在我的情况下,我要搜索的类别的条目是“案例研究”,它需要搜索该类别的博客文章中的所有内容。返回链接,图像,标题。

1 个答案:

答案 0 :(得分:2)

税收查询并非如此。您期望的结果实际上应该更简单。

查看修改后的代码(带有注释,说明发生了什么事):

function advanced_search_query( $query ) {
    if( $query->is_search() ) {
        // find the category by slug
        $term = get_category_by_slug( 'case-study' ); 
        // get the category ID
        $id = $term->term_id;
        // set the query argument to search within the category
        $query->set( 'cat', $cat_id );
    }

    // removed "return $query" - $query is passed by reference, so no need to return
}

add_action('pre_get_posts', 'advanced_search_query');

注意:这将导致所有搜索仅限于此类别。由于我猜想这不是您想要的,所以我建议您对表单以及函数进行以下修改,因此仅在搜索源于表单时才限制搜索:

<form method="get" id="advanced-searchform" role="search" action="<?php echo esc_url( home_url( '/' ) ); ?>">
    <input type="hidden" name="search" value="post">
    <input id="search-case-study" class="search-case-study" type="text" value="" placeholder="Search..." name="s" />
    <!-- add a hidden input that passes the desired category slug -->
    <input name="cat_slug" value="case-study" />
    <input type="submit" id="searchsubmit" value="Search" />
</form>

然后,按如下所示更新functions.php函数:

function advanced_search_query( $query ) {
    // check if search AND if "cat_slug" input was present
    if( $query->is_search() && ! empty( $_GET['cat_slug'] ) ) {
        // find the category by the slug passed in the input
        $term = get_category_by_slug( $_GET['cat_slug'] ); 
        // defensive check, in case the category could not be found
        if ( ! empty( $term->term_id ) ) {
            // get the category ID
            $cat_id = $term->term_id;
            // set the query argument to search within the category
            $query->set( 'cat', $cat_id );
        }
    }

    // removed "return $query" - $query is passed by reference, so no need to return
}

add_action('pre_get_posts', 'advanced_search_query');