LoginSignup
4
5

More than 5 years have passed since last update.

【wordpress】サイト内検索でカスタム投稿を含める

Posted at

ロジック忘れないように忘備録

functions.phpなどに

/**
 * 検索ロジックカスタマイズ
 *
 */
function customSearcher($search, $wp_query) {
    if ( $wp_query->is_main_query() && $wp_query->is_search() && !is_admin() ) {
        $q = $wp_query->query_vars;
        $n = null;
        if (!empty($q['s'])) {

            $keyword = mb_convert_kana($q['s'], 's');
            $keywords = preg_split('/[\s]+/', $keyword, -1, PREG_SPLIT_NO_EMPTY);

            foreach ($keywords as $word) {
                $n = " OR ( pm.meta_key IN ( 'search_data' ) AND pm.meta_value LIKE '%" . $word . "%') ";

                $search = str_replace( "post_content LIKE '%". $word .  "%')", "post_content LIKE '%". $word .  "%')" . $n , $search );
            }

        }

    }
    return $search;
}
add_filter('posts_search', 'customSearcher', 10, 2);
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5