Wordpress搜索标题(但不完全)

时间:2016-08-04 08:26:42

标签: wordpress search

我网站上有数以千计的woocommerce产品,我的wordpress搜索工作非常慢。所以我试图只搜索标题来加速我的搜索,我发现了这个:

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( like_escape( $term ) );

$search .= "{$searchand}($wpdb->posts.post_title REGEXP '[[:<:]]{$term}[[:>:]]')";

$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', 1000, 2 );

但它用大写/小写敏感搜索确切的单词,我不希望这样。例如,我是一个名为&#34; 795PA&#34;的产品。当我搜索&#34; 795pa&#34;没有结果。我该如何解决这个问题?想法?

1 个答案:

答案 0 :(得分:0)

我无法看到差异,但是那些小代码解决了我的问题。这是修复:

//Limit Search to Post Titles Only
function ni_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( like_escape( $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', 'ni_search_by_title_only', 500, 2 );

我不知道我可以在这里分享链接,但nathan ingram分享了这些链接。