プラグインWooCommerceのwp_search_stopwordsフィルタの使用方法・解説

概要

wp_search_stopwordsフィルタは、WordPressの検索機能において除外すべきストップワードをカスタマイズするために使用されます。ストップワードとは、検索しても意味を持たない単語のことで、これらを除外することでユーザーがより関連性の高い検索結果を得ることができます。このフィルタは、特定の条件やニーズに応じて、ストップワードのリストを自由に変更できるため、以下のような場面でよく使用されます:

  1. 特定の業界用語を検索対象にしたい場合
  2. 多言語対応のサイトで言語ごとに異なるストップワードを設定したい場合
  3. ユーザーのフィードバックに基づいて検索結果を改善したい場合
  4. CMS上でのカスタムコンテンツに特化した検索体験を提供したい場合
  5. 他のプラグインやテーマとも連携し、ユーザー体験を向上させたい場合
  6. SEO対策の一環として、検索結果の精度を向上させたい場合

このフィルタは、WooCommerceプラグインのバージョンやWordPress本体のバージョンに関連付けられており、さまざまなカスタマイズが可能です。

構文

add_filter('wp_search_stopwords', 'custom_stopwords_function');

パラメータ

  • $stopwords: 既存のストップワードの配列。

戻り値

  • 修正されたストップワードの配列。

使用可能なバージョン

  • WooCommerce: バージョン 3.0 以上
  • WordPress: バージョン 4.4 以上

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード1

function custom_search_stopwords($stopwords) {
    $stopwords[] = 'customword';
    return $stopwords;
}
add_filter('wp_search_stopwords', 'custom_search_stopwords');

このコードは、デフォルトのストップワードに「customword」を追加するカスタムフィルタです。

サンプルコード2

function modify_default_stopwords($stopwords) {
    return array_unique(array_merge($stopwords, ['example', 'test']));
}
add_filter('wp_search_stopwords', 'modify_default_stopwords');

デフォルトのストップワードに「example」と「test」を追加し、重複を排除するサンプル。

サンプルコード3

function remove_unwanted_stopwords($stopwords) {
    $unwanted_words = ['the', 'and', 'is'];
    return array_diff($stopwords, $unwanted_words);
}
add_filter('wp_search_stopwords', 'remove_unwanted_stopwords');

ストップワードから「the」、「and」、「is」を削除することを目的としたコードです。

サンプルコード4

function replace_stopwords($stopwords) {
    return ['newword1', 'newword2'];
}
add_filter('wp_search_stopwords', 'replace_stopwords');

ストップワードを新しい単語の配列で置き換えるサンプルコードです。

サンプルコード5

function custom_stopwords_for_languages($stopwords) {
    if (get_locale() === 'ja') {
        $stopwords[] = 'による';
    }
    return $stopwords;
}
add_filter('wp_search_stopwords', 'custom_stopwords_for_languages');

言語に基づいてストップワードを追加するカスタマイズの例で、日本語のロケール用に「による」を追加します。

この関数について質問する


上の計算式の答えを入力してください