WordPressの検索結果にカスタムフィールドの値を追加する

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function cf_search_join( $join ) {
    global $wpdb;
    if ( is_search() ) {
        $join .= ' LEFT JOIN ' . $wpdb->postmeta . ' ON ' . $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
    }
    return $join;
}
add_filter( 'posts_join', 'cf_search_join' );
 
function cf_search_where( $where ) {
    global $wpdb;
    if ( is_search() ) {
        $where = preg_replace(
            "/\(\s*" . $wpdb->posts . ".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
            "(" . $wpdb->posts . ".post_title LIKE $1) OR (" . $wpdb->postmeta . ".meta_value LIKE $1)", $where );
 
        // 特定のカスタムフィールドを検索対象から外す(※1)
//      $where .= " AND (" . $wpdb->postmeta . ".meta_key NOT LIKE 'number')";
//      $where .= " AND (" . $wpdb->postmeta . ".meta_key NOT LIKE 'zip')";
//      $where .= " AND (" . $wpdb->postmeta . ".meta_key NOT LIKE 'access')";
    }
    return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
 
function cf_search_distinct( $where ) {
    global $wpdb;
    if ( is_search() ) {
        return "DISTINCT";
    }
    return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
 
// 検索対象を『タイトルのみ』にする
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 );// (※2)

下記サイトを参考にしました。
WordPress内の検索対象にカスタムフィールドも適用する