WordPress 查询搜索的确切单词

Ale*_*vić 5 php regex wordpress word-boundaries

我想将关键字搜索限制为仅搜索确切的单词而不是短语或混合内容,因此如果我搜索cheese它需要仅限于单词cheese,现在它也会返回包含单词 的内容cheeseburger

我修改后的模板查询中的搜索查询部分就在这里:

if ( ! function_exists( 'get_job_listings' ) ) :
    if ( 'top_rating' === $args['orderby'] ) {
        $query_args['meta_query'] = [
            'relation' => 'OR',
            [
                'key'     => 'rating',
                'compare' => 'EXISTS',
            ],
            [
                'key'     => 'rating',
                'compare' => 'NOT EXISTS',
            ],
        ];
        $query_args['orderby'] = [
            'meta_value_num' => 'DESC',
            'comment_count' => 'DESC',
        ];
    }

    $job_manager_keyword = sanitize_text_field( $args['search_keywords'] );
    if ( ! empty( $job_manager_keyword ) && strlen( $job_manager_keyword ) >= apply_filters( 'job_manager_get_listings_keyword_length_threshold', 2 ) ) {
        $search_query = $job_manager_keyword;
    $query_args['s'] = $search_query;
        // $query_args['s'] = '"' . $search_query . '"';
        // $query_args['s'] = '/\b' . preg_quote($search_query, '/') . '\b/';
        $query_args['sentence'] = true;
        add_filter( 'posts_search', 'get_job_listings_keyword_search' );
    }

    $query_args = apply_filters( 'job_manager_get_listings', $query_args, $args );

    if ( empty( $query_args['meta_query'] ) ) {
        unset( $query_args['meta_query'] );
    }

    if ( empty( $query_args['tax_query'] ) ) {
        unset( $query_args['tax_query'] );
    }

    /** This filter is documented in wp-job-manager.php */
    $query_args['lang'] = apply_filters( 'wpjm_lang', null );

    // Filter args.
    $query_args = apply_filters( 'get_job_listings_query_args', $query_args, $args );
    do_action( 'before_get_job_listings', $query_args, $args );

    // Cache results.
    if ( apply_filters( 'get_job_listings_cache_results', true ) ) {
        $to_hash              = wp_json_encode( $query_args );
        $query_args_hash      = 'jm_' . md5( $to_hash . JOB_MANAGER_VERSION ) . WP_Job_Manager_Cache_Helper::get_transient_version( 'get_job_listings' );
        $result               = false;
        $cached_query_results = true;
        $cached_query_posts   = get_transient( $query_args_hash );

        if ( is_string( $cached_query_posts ) ) {
            $cached_query_posts = json_decode( $cached_query_posts, false );

            if (
                $cached_query_posts
                && is_object( $cached_query_posts )
                && isset( $cached_query_posts->max_num_pages )
                && isset( $cached_query_posts->found_posts )
                && isset( $cached_query_posts->posts )
                && is_array( $cached_query_posts->posts )
            ) {
                if ( in_array( $query_args['fields'], [ 'ids', 'id=>parent' ], true ) ) {
                    // For these special requests, just return the array of results as set.
                    $posts = $cached_query_posts->posts;
                } else {
                    $posts = array_map( 'get_post', $cached_query_posts->posts );
                }

                $result = new WP_Query();
                $result->parse_query( $query_args );
                $result->posts         = $posts;
                $result->found_posts   = intval( $cached_query_posts->found_posts );
                $result->max_num_pages = intval( $cached_query_posts->max_num_pages );
                $result->post_count    = count( $posts );
            }
        }

        if ( false === $result ) {
            $result               = new WP_Query( $query_args );
            $cached_query_results = false;
            $cacheable_result                  = [];
            $cacheable_result['posts']         = array_values( $result->posts );
            $cacheable_result['found_posts']   = $result->found_posts;
            $cacheable_result['max_num_pages'] = $result->max_num_pages;
            set_transient( $query_args_hash, wp_json_encode( $cacheable_result ), DAY_IN_SECONDS );
        }

        if ( $cached_query_results ) {
            // random order is cached so shuffle them.
            if ( 'rand_featured' === $args['orderby'] ) {
                usort( $result->posts, '_wpjm_shuffle_featured_post_results_helper' );
            } elseif ( 'rand' === $args['orderby'] ) {
                shuffle( $result->posts );
            }
        }
    } else {
        $result = new WP_Query( $query_args );
    }
    do_action( 'after_get_job_listings', $query_args, $args );

    //remove_filter( 'posts_search', 'get_job_listings_keyword_search' );
    return $result;
}

endif;
Run Code Online (Sandbox Code Playgroud)

我可以看到这$query_args['s']是搜索关键字的标准查询,但我尝试过的一些标准查询修改如下例所示:

还有其他例子,但它们都不适合我。

我该如何修改它,以便它只能搜索内容中的确切单词?

我看到这个问题已发布多次,但我尝试过的所有示例都不起作用。

sil*_*ver 1

熟悉 SQL 语法,并且更容易定制由 wordpress 执行的任何查询

您可以使用posts_clauses过滤器直接修改任何查询,包括搜索查询

LIKE默认情况下,wordpress 使用并环绕搜索词对帖子标题、帖子内容和帖子 Excerot 执行搜索%,语法如下

WHERE 1=1 
AND (
    post_table.post_title LIKE '%hello%' OR 
    post_table.post_excerpt LIKE '%hello%' OR
    post_table.content LIKE '%hello%'
)
Run Code Online (Sandbox Code Playgroud)

它甚至将每个单词分解成一个单独的 LIKE 语句,

但是,由于您想要进行精确匹配,因此您可以在搜索词之间添加一个空格,然后在第一个或最后一个匹配项之间添加另一个匹配项,如下所示在post_content列中搜索字符串

WHERE 1=1 
AND (
    post_table.post_content LIKE 'hello %' OR  //hello is first word, match on -> hello world
    post_table.post_content LIKE '% hello %' OR //hello is in between words, match on -> world hello world
    post_table.post_content LIKE '% hello' //hello is the last word, match on -> world hello
)
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用的是支持正则表达式的 > MYSQL 8,则可以使用边界执行字符串搜索,例如 ;

WHERE 1=1 
AND (
    post_table.post_content RLIKE "[[:<:]]hello[[:>:]]"
) 
Run Code Online (Sandbox Code Playgroud)

现在修改搜索查询非常简单,参考下面的代码

add_filter( 'posts_clauses', function ($clauses, $query) {
    
    // prevent query modification if its not search page or an admin page or not main query
    if ( !$query->is_search || is_admin() || !$query->is_main_query()) 
            return $clauses;
    
    // get the search term
    $searchTerm = sanitize_text_field( $query->query['s'] );
    
    //build the search query, and perfom the search on post_title and post_content column
    //refer to two functions below
    $searchQuery = _custom_search_query($searchTerm, ['post_title', 'post_content']);
    
    //override wordpress default search query by defining the where key on its clauses
    $clauses['where'] = "AND ( $searchQuery )";
    
    // additional filter on what you want to search
    $clauses['where'] .= " AND wp_posts.post_type = 'post' AND wp_posts.post_status = 'publish'";
    
    //add the default order
    $clauses['orderby'] = "wp_posts.post_title DESC, wp_posts.post_date DESC";
    
    return $clauses;
}, 10, 2 );
Run Code Online (Sandbox Code Playgroud)

为了避免手动输入所有LIKESOR's,我们可以根据您想要的查询方式使用下面这两个函数,

用于在指定搜索的不同字段上进行条件构建LIKE和语句OR

function _custom_search_query( $term, $fields = [] ) {
    
    $query = '';
    $compares = ["$term %", "% $term", "% $term %"];
    foreach ($fields as $key => $field) {
        foreach ($compares as $k => $comp) {
            $query .= ($key > 0 || $k > 0 ? ' OR' : '' ). " wp_posts.$field LIKE '$comp'";
        }
    }
    return $query;
}
Run Code Online (Sandbox Code Playgroud)

用于在指定搜索的不同字段上进行条件构建RLIKE和语句OR

function _regex_custom_search_query(  $term, $fields = [] ) {
    $query = '';
    foreach ($fields as $key => $field) {
        $query .= ($key > 0 ? ' OR' : '' ). ' wp_posts.'.$field.' RLIKE "[[:<:]]'.$term.'[[:>:]]"' ;
    }
    return $query;
}
Run Code Online (Sandbox Code Playgroud)

$wp_query->request另外,在前端搜索页面上打印,您将看到当前页面上执行的 SQL,这将帮助您调试任何问题 ei

add_action('wp_head', function() {
    global $wp_query;

    if ( !$wp_query->is_search )
        return;
    
    echo '<pre>', print_r($wp_query->request, 1), '</pre>';
    
});
Run Code Online (Sandbox Code Playgroud)

如果您还想创建自己的搜索页面,则只需使用以下命令应用相同的查询即可$wpdb