プラグインWooCommerceのwoocommerce_settings_sanitize_title$VALUE[id]フィルタの使用方法・解説

概要

woocommerce_settings_sanitize_title$VALUE[id] フィルタは、WooCommerceの設定オプションのタイトルをサニタイズする際に使用されます。このフィルタを利用することで、タイトルをカスタマイズしたり、特定の条件に基づいて処理を変更することが可能です。

使用頻度の高い機能例

このフィルタは、以下のような機能実装に役立ちます。

  1. 設定画面のタイトルをカスタムする
  2. 特定の条件に応じてタイトルを変更する
  3. 特殊文字の削除や変換
  4. 大文字・小文字の統一
  5. タイトルの前後にプレフィックスやサフィックスを追加する
  6. タイトルの重複チェックを行う

構文

add_filter('woocommerce_settings_sanitize_title$VALUE[id]', 'custom_function_name', 10, 1);

パラメータ

  • $VALUE: フィルタ対象の設定オプションの情報を含む配列
  • id: フィルタに適用される設定オプションのID

戻り値

フィルタによって加工されたタイトルを返す。

対応するバージョン

  • WooCommerce: バージョン4.0以降
  • WordPress: バージョン5.0以降

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

アクション 使用例
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: 特定の条件に応じたタイトルの変更

add_filter('woocommerce_settings_sanitize_title$VALUE[your_setting_id]', 'change_title_conditionally');
function change_title_conditionally($title) {
    if (some_condition()) {
        return '新しいタイトル';
    }
    return $title;
}

このサンプルは、特定の条件満たす場合にのみタイトルを「新しいタイトル」に変更します。

サンプル 2: 特殊文字の削除

add_filter('woocommerce_settings_sanitize_title$VALUE[your_setting_id]', 'remove_special_characters');
function remove_special_characters($title) {
    return preg_replace('/[^a-zA-Z0-9s]/', '', $title);
}

このサンプルでは、タイトルから特別な文字を削除します。

サンプル 3: タイトルの大文字・小文字の統一

add_filter('woocommerce_settings_sanitize_title$VALUE[your_setting_id]', 'sanitize_title_case');
function sanitize_title_case($title) {
    return strtolower($title);
}

このサンプルは、タイトルをすべて小文字に変換します。

サンプル 4: タイトルの前にプレフィックスを追加

add_filter('woocommerce_settings_sanitize_title$VALUE[your_setting_id]', 'add_prefix_to_title');
function add_prefix_to_title($title) {
    return 'PREFIX_' . $title;
}

このサンプルは、タイトルの前に「PREFIX_」を追加します。

サンプル 5: 重複チェックの実装

add_filter('woocommerce_settings_sanitize_title$VALUE[your_setting_id]', 'check_duplicate_title');
function check_duplicate_title($title) {
    $existing_titles = get_existing_titles();
    if (in_array($title, $existing_titles)) {
        return $title . '_dup';
    }
    return $title;
}

このサンプルは、既存のタイトルの中に同名のものがある場合、タイトルに「_dup」を追加します。

引用元: WordPress Codex

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


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