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

概要

woocommerce_shipping_zone_method_status_toggled は、WooCommerce の配送方法のステータスが切り替えられた際に発火するアクションフックです。このアクションは、特に配送方法の管理やカスタマイズに関係する場面で利用されます。具体的には以下のような機能を実装する際によく使用されます。

  1. 配送方法の有効化・無効化の通知機能
  2. 配送方法が変更された際のカスタムログの記録
  3. 管理画面におけるカスタムメッセージの表示
  4. データベースの状態を更新する処理
  5. 他のプラグインとの連携におけるトリガー
  6. ユーザーインターフェースのカスタマイズ

このアクションは、WooCommerce バージョン 2.6 以降と、WordPress の最新バージョンで使用可能です。

構文

add_action( 'woocommerce_shipping_zone_method_status_toggled', 'your_function', 10, 2 );

パラメータ

  1. $method_id (string) – 変更された配送方法の ID。
  2. $zone_id (int) – 対応する配送ゾーンの ID。

戻り値

このアクションは戻り値を持ちませんが、フックされた関数内で任意の処理を行うことができます。

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

アクション名 使用例
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_status_toggled', 'notify_status_change', 10, 2 );

function notify_status_change( $method_id, $zone_id ) {
    $message = sprintf( '配送方法 %s がゾーン %s で変更されました。', $method_id, $zone_id );
    error_log( $message );
}

このサンプルは、配送方法のステータスが変更されたときに、その情報をエラーログに記録します。

サンプルコード2: ステータス変更時にメッセージを表示

add_action( 'woocommerce_shipping_zone_method_status_toggled', 'display_custom_message', 10, 2 );

function display_custom_message( $method_id, $zone_id ) {
    add_settings_error( 'general', 'status_change', '配送方法 ' . $method_id . ' のステータスが変更されました。', 'updated' );
}

このコードは、配送方法のステータスが変更されたときに、管理画面にカスタムメッセージを表示します。

サンプルコード3: ステータス切替時に外部APIを呼び出す

add_action( 'woocommerce_shipping_zone_method_status_toggled', 'call_external_api', 10, 2 );

function call_external_api( $method_id, $zone_id ) {
    wp_remote_post( 'https://example.com/api/update-status', array(
        'body' => json_encode( array( 'method_id' => $method_id, 'zone_id' => $zone_id ) ),
        'headers' => array( 'Content-Type' => 'application/json' ),
    ));
}

このサンプルは、配送方法のステータスが変更された際に外部APIにデータを送信します。

サンプルコード4: データベースの更新

add_action( 'woocommerce_shipping_zone_method_status_toggled', 'update_database_on_status_change', 10, 2 );

function update_database_on_status_change( $method_id, $zone_id ) {
    global $wpdb;
    $wpdb->update( 'wp_shipping_methods',
        array( 'status' => 'updated' ),
        array( 'method_id' => $method_id, 'zone_id' => $zone_id )
    );
}

このコードは、配送方法のステータスが切り替わった際に、データベースの特定のテーブルを更新します。

サンプルコード5: カスタム条件での処理

add_action( 'woocommerce_shipping_zone_method_status_toggled', 'conditional_processing', 10, 2 );

function conditional_processing( $method_id, $zone_id ) {
    if ( $method_id === 'flat_rate' ) {
        // 特定の配送方法に対して何らかの処理を行う
    }
}

このサンプルは、特定の配送方法(ここではフラットレート)が変更された際にのみ特定の処理を実行します。

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


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