讓 WordPress 隻搜索文章的標題

WordPress 默認的搜索功能還真挺弱的,搜索出來的結果很不符合人意,如果你想讓它檢索出來的結果更加相關,可以限定隻搜索文章的標題,將下面的代碼添加到主題的 functions.php 文件即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * 讓 WordPress 隻搜索文章的標題
 * https://www.wpdaxue.com/search-by-title-only.html
 */
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 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', 500, 2 );

/**
* 讓 WordPress 隻搜索文章的標題
* https://www.wpdaxue.com/search-by-title-only.html
*/
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 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’, 500, 2 );

參考資料:http://wordpress.stackexchange.com/questions/11822/

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *