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

概要

woocommerce_shipping_zone_method_added アクションは、WooCommerceの配送方法が配送ゾーンに追加されたときに発火するフックです。このアクションを使用することで、特定の配送方法が追加された後にカスタム処理を実行することができます。

このアクションは以下のような状況でよく使われます:

  1. 特定の配送方法に基づく価格の変更。
  2. 追加情報を保存するためのカスタムメタデータの挿入。
  3. 配送方法が追加される度に管理者への通知を行う。
  4. 特定の条件に基づいて配送方法の有効/無効を切り替える。
  5. 複数の配送方法を自動的に設定するための処理。
  6. カスタムロジックに基づく配送オプションの調整。

構文

do_action( 'woocommerce_shipping_zone_method_added', $instance_id, $shipping_method, $zone );

パラメータ

  • $instance_id (int): 追加された発送方法のインスタンスID。
  • $shipping_method (object): 追加された発送方法のインスタンス。
  • $zone (object): 追加された配送ゾーンのインスタンス。

戻り値

このアクションは値を返しません(void)。

使用可能なバージョン

  • WooCommerce: バージョン3.0.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_action( 'woocommerce_shipping_zone_method_added', 'log_shipping_method', 10, 3 );

function log_shipping_method( $instance_id, $shipping_method, $zone ) {
    error_log( 'Shipping method added: ' . $shipping_method->id );
}

引用元: https://developer.woocommerce.com

サンプル2: 配送方法による価格調整

特定の配送方法が追加された際に、その料金を変更する処理です。

add_action( 'woocommerce_shipping_zone_method_added', 'adjust_shipping_price', 10, 3 );

function adjust_shipping_price( $instance_id, $shipping_method, $zone ) {
    if ( 'flat_rate' === $shipping_method->id ) {
        $shipping_method->cost = 10; // 固定料金に設定
    }
}

引用元: https://developer.woocommerce.com

サンプル3: 管理者に通知

配送方法が追加された際に、管理者に通知メールを送信する例です。

add_action( 'woocommerce_shipping_zone_method_added', 'notify_admin_shipping_method', 10, 3 );

function notify_admin_shipping_method( $instance_id, $shipping_method, $zone ) {
    $admin_email = get_option( 'admin_email' );
    wp_mail( $admin_email, '新しい配送方法が追加されました', '配送方法: ' . $shipping_method->id );
}

引用元: https://developer.woocommerce.com

サンプル4: カスタムメタデータの保存

配送方法が追加された際に、カスタムメタデータを保存する例です。

add_action( 'woocommerce_shipping_zone_method_added', 'save_custom_meta_data', 10, 3 );

function save_custom_meta_data( $instance_id, $shipping_method, $zone ) {
    update_option( 'custom_shipping_meta_' . $instance_id, 'custom_value' );
}

引用元: https://developer.woocommerce.com

サンプル5: 条件による配送方法の有効化/無効化

特定の条件に基づいて配送方法の有効/無効を切り替えるサンプルです。

add_action( 'woocommerce_shipping_zone_method_added', 'conditional_shipping_method_status', 10, 3 );

function conditional_shipping_method_status( $instance_id, $shipping_method, $zone ) {
    if ( 'free_shipping' === $shipping_method->id && !is_user_logged_in() ) {
        $shipping_method->enabled = 'no'; // ログインしていない場合は無効化
    }
}

引用元: https://developer.woocommerce.com

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


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