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

概要

woocommerce_payment_gateway_supports フィルタは、WooCommerce の決済ゲートウェイが特定の機能をサポートしているかどうかを判断するために使用されます。このフィルタを使うことで、プラグインやテーマの開発者は、特定の決済ゲートウェイの機能を追加したりカスタマイズしたりすることが可能です。一般的に、このフィルタは以下のような機能を実装する際によく使われます:

  1. 特定の決済メソッドの有効化/無効化
  2. カスタムフィールドの表示/非表示
  3. アップセルやクロスセルの機能追加
  4. ユーザーインターフェースのカスタマイズ
  5. サードパーティーサービスとの統合
  6. 特定の条件に基づく機能制限

構文

add_filter('woocommerce_payment_gateway_supports', 'your_function_name', 10, 3);

パラメータ

  1. $supports – 対象の決済ゲートウェイがサポートする機能の配列。
  2. $gateway – 現在の決済ゲートウェイのインスタンス。
  3. $order – 現在の注文オブジェクト。

戻り値

$supports – 更新された機能の配列。

使用可能なバージョン

  • WooCommerce バージョン: 3.0以上
  • WordPress バージョン: 4.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_payment_gateway_supports', 'add_custom_feature', 10, 2);
function add_custom_feature($supports, $gateway) {
    if ('my_custom_gateway' === $gateway->id) {
        $supports[] = 'custom_feature';
    }
    return $supports;
}

このサンプルコードは、”my_custom_gateway” という決済ゲートウェイに “custom_feature” という機能を追加します。

サンプルコード 2: 特定の条件で機能を無効にする

add_filter('woocommerce_payment_gateway_supports', 'disable_feature_based_on_condition', 10, 2);
function disable_feature_based_on_condition($supports, $gateway) {
    if (is_user_logged_in() && 'my_special_gateway' === $gateway->id) {
        unset($supports[array_search('some_feature', $supports)]);
    }
    return $supports;
}

このコードは、特定のゲートウェイがログインユーザーに対して「some_feature」を無効にします。

サンプルコード 3: 複数の機能を追加する

add_filter('woocommerce_payment_gateway_supports', 'add_multiple_features', 10, 2);
function add_multiple_features($supports, $gateway) {
    if ('another_gateway' === $gateway->id) {
        $supports = array_merge($supports, ['feature_one', 'feature_two']);
    }
    return $supports;
}

このコードは、”another_gateway” の決済ゲートウェイに複数の機能を追加しています。

サンプルコード 4: 支払い方法を条件付きで表示

add_filter('woocommerce_payment_gateway_supports', 'conditional_display_payment_method', 10, 2);
function conditional_display_payment_method($supports, $gateway) {
    if (!is_cart() && 'credit_card_gateway' === $gateway->id) {
        $supports[] = 'conditional_display';
    }
    return $supports;
}

このサンプルは、「credit_card_gateway」がカートページ以外でのみ表示されるように条件を設定しています。

サンプルコード 5: 特定の機能をサポートの除外

add_filter('woocommerce_payment_gateway_supports', 'exclude_feature', 10, 2);
function exclude_feature($supports, $gateway) {
    if ('restricted_gateway' === $gateway->id) {
        if (in_array('some_feature', $supports)) {
            $supports = array_diff($supports, ['some_feature']);
        }
    }
    return $supports;
}

このコードは、”restricted_gateway” の決済ゲートウェイから「some_feature」を除外します。

このサンプルコードはすべて著作権フリーのものです。

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


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