プラグインWooCommerceのwoocommerce_shipping_method_chosenアクションの使用方法・解説

概要

woocommerce_shipping_method_chosenアクションは、WooCommerce(バージョン3.0以降)で、配送方法が選択された際に実行されるフックです。このアクションは、ユーザーがカート内の商品を購入する際に選択した配送方法に基づいて、さまざまな機能を実装するのに役立ちます。以下に挙げる機能の実装時によく使われます。

  1. 配送コストの計算のカスタマイズ
  2. 送料割引の適用
  3. 他のフィールドの表示/非表示の制御
  4. 特定の配送方法に基づくカスタムメッセージの表示
  5. カートページの再計算トリガー
  6. 特定の条件に基づいてカスタムアクションを追加

このアクションの構文は次の通りです:

do_action( 'woocommerce_shipping_method_chosen', $chosen_method, $available_methods );

パラメータ

  • $chosen_method: ユーザーが選択した配送方法のID(文字列)
  • $available_methods: 利用可能な配送方法の配列

戻り値

このアクションは何も戻しません。

使用可能なプラグインバージョン

  • WooCommerce : 3.0以上

使用可能なWordPressバージョン

  • 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_action( 'woocommerce_shipping_method_chosen', 'custom_shipping_method_message', 10, 2 );
function custom_shipping_method_message( $chosen_method, $available_methods ) {
    if ( $chosen_method === 'flat_rate:1' ) {
        echo '<p>選択された配送方法: 平坦な料金です。';
    }
}

このサンプルコードは、ユーザーが「flat_rate:1」という配送方法を選択した場合、カスタムメッセージを画面に表示します。引用元: https://woocommerce.com

サンプルコード2:配送コストの自動更新

add_action( 'woocommerce_shipping_method_chosen', 'update_shipping_cost_on_method_change', 10, 2 );
function update_shipping_cost_on_method_change( $chosen_method, $available_methods ) {
    if ( ! empty( $available_methods ) ) {
        WC()->cart->calculate_shipping();
    }
}

このコードは、配送方法が選択された時に自動的に送料の再計算を行います。引用元: https://woocommerce.com

サンプルコード3:特定の配送方法に対する割引の適用

add_action( 'woocommerce_shipping_method_chosen', 'apply_discount_based_on_shipping_method', 10, 2 );
function apply_discount_based_on_shipping_method( $chosen_method, $available_methods ) {
    if ( $chosen_method === 'free_shipping:1' ) {
        WC()->cart->add_fee( '特別割引', -10 );
    }
}

このサンプルでは、ユーザーが「free_shipping:1」という配送方法を選んだ場合に、カートに10ドルの割引を適用します。引用元: https://woocommerce.com

サンプルコード4:カスタム配送オプションの表示

add_action( 'woocommerce_shipping_method_chosen', 'show_custom_shipping_option', 10, 2 );
function show_custom_shipping_option( $chosen_method, $available_methods ) {
    echo '<p>ご希望の配送オプションを選択してください。</p>';
}

このサンプルコードは、配送方法が選ばれた際にカスタムメッセージを表示します。引用元: https://woocommerce.com

サンプルコード5:特定の条件でメッセージを変更

add_action( 'woocommerce_shipping_method_chosen', 'conditional_shipping_message', 10, 2 );
function conditional_shipping_message( $chosen_method, $available_methods ) {
    if ( $chosen_method === 'local_pickup:1' ) {
        echo '<p>ローカルピックアップを選択しました。住所の入力は不要です。</p>';
    }
}

このコードは、ユーザーが「local_pickup:1」という配送方法を選択した場合に特定のメッセージを表示します。引用元: https://woocommerce.com

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


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