🔍

WordPressでプラグインを使用しないで文字列検索する

2023.04.13

SHARE

TABLE OF CONTENTS

    🔍

    WordPressでプラグインを使用しないで文字列検索する

    2023.04.13

    PHPコード

    function custom_search( $search, $wp_query ) {
      global $wpdb;
      if ( ! isset( $wp_query->query_vars ) ) return $search;
    
      if ( isset( $wp_query->query_vars['s'] ) ) {
        // 検索ワードを文字列で取得する
        $search_words = esc_html(get_search_query());
    
        // 文字列による複数検索を可能するため「全角スペース」を「半角スペース」に変更する
        $search_words = str_replace(' ', ' ', $search_words);
    
        // 文字列を配列にする
        $search_words = explode(' ', $search_words);
      
        // 検索SQL文実行
        if ( count( $search_words ) > 0 ) {
          $search = '';
          foreach ( $search_words as $word ) {
            if ( ! empty( $word ) ) {
              $search_word        = '%' . esc_sql( $word ) . '%';
              $posts              = esc_sql( $wpdb->posts );
              $users              = esc_sql( $wpdb->users );
              $term_relationships = esc_sql( $wpdb->term_relationships );
              $term_taxonomy      = esc_sql( $wpdb->term_taxonomy );
              $terms              = esc_sql( $wpdb->terms );
              $postmeta           = esc_sql( $wpdb->postmeta );
              $search     .= " AND (
                  {$posts}.post_title LIKE '{$search_word}'
                  OR {$posts}.post_content LIKE '{$search_word}'
                  OR {$posts}.post_author IN (
                      SELECT distinct ID
                      FROM {$users}
                      WHERE display_name LIKE '{$search_word}'
                  )
                  OR {$posts}.ID IN (
                      SELECT distinct r.object_id
                      FROM {$term_relationships} AS r
                      INNER JOIN {$term_taxonomy} AS tt ON r.term_taxonomy_id = tt.term_taxonomy_id
                      INNER JOIN {$terms} AS t ON tt.term_id = t.term_id
                      WHERE t.name LIKE '{$search_word}'
                      OR t.slug LIKE '{$search_word}'
                      OR tt.description LIKE '{$search_word}'
                  )
                  OR {$posts}.ID IN (
                      SELECT distinct p.post_id
                      FROM {$postmeta} AS p
                      WHERE p.meta_value LIKE '{$search_word}'
                  )
              ) ";
            };
          };
        };
        return $search;
      };
    };
    
    add_filter( 'posts_search', 'custom_search', 10, 2 );

    Reference

    ©2025 SHOYA KAJITA.