0

我正在尝试通过使用 pre_get_posts 挂钩来修改自定义 wordpress 搜索,以便不会在产品描述中搜索特定单词。

add_action( 'pre_get_posts', 'exclude_search_content' );
function exclude_search_content( $Q ) {

    $search_phrase = $Q->query['s'];

    if( $Q->is_search() ) {
        /** Dont search for $search_phrase in excerpt and product description
        * search only product title, a meta key and a taxonomy.
        */
    }
}

它似乎比我预期的要复杂。有任何想法吗?

4

1 回答 1

0

如果您查看posts_search 参考资料 ,您会发现一些Contribute 已经编写了类似的功能,所以我只是对其进行了测试,它工作正常。

function search_by_title_only($search, $wp_query)
{
    global $wpdb;
    if (empty($search)) {
        return $search; // skip processing - no search term in query
    }
    $q = $wp_query->query_vars;
    $n = !empty($q['exact']) ? '' : '%';
    $search =
    $searchand = '';
    foreach ((array) $q['search_terms'] as $term) {
        $term = esc_sql($wpdb->esc_like($term));
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }
    if (!empty($search)) {
        $search = " AND ({$search}) ";
        if (!is_user_logged_in()) {
            $search .= " AND ($wpdb->posts.post_password = '') ";
        }

    }

    return $search;
}
add_filter('posts_search', 'search_by_title_only', 20, 2);
于 2018-08-28T12:26:17.063 回答