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

概要

woocommerce_webhook_statuses アクションは、WooCommerce のウェブフックの状態を管理するためのフックです。このアクションは、特定のイベントが発生した際に、カスタマイズされたウェブフックの状態を変更したり、他の独自機能を実装するために使用されます。

この アクションがよく使われる機能は以下の通りです:

  1. ウェブフックのステータスのカスタマイズ
  2. 外部サービスへの通知の送信
  3. 売上統計の集計
  4. ユーザーアクションに応じたリアルタイムのデータ処理
  5. デバッグ情報の収集
  6. 特定条件に基づく通知のフィルタリング

構文

add_action('woocommerce_webhook_statuses', 'your_function_name', 10, 2);

パラメータ

このアクションには、以下の2つのパラメータがあります:

  1. $statuses: 現在のウェブフックのステータスを表す配列。
  2. $webhook: 対応するウェブフックオブジェクト。

戻り値

このアクションは特定の戻り値を持たないため、主にサイドエフェクトを持つカスタムロジックを実行するために使用されます。

互換性

  • WooCommerce バージョン: 3.0.0以上
  • WordPress バージョン: 4.0以上

サンプルコード

サンプル1: ウェブフック状態の追加

このサンプルコードでは、新たなウェブフック状態を追加しています。

add_action('woocommerce_webhook_statuses', 'add_custom_webhook_status', 10, 2);

function add_custom_webhook_status($statuses, $webhook) {
    $statuses['custom_status'] = __('Custom Status', 'text-domain');
    return $statuses;
}

(サンプルコードの引用元: WordPress Codex)

サンプル2: ステータスに基づくログ記録

ウェブフックのステータスに応じて、ログを記録するサンプルです。

add_action('woocommerce_webhook_statuses', 'log_webhook_status', 10, 2);

function log_webhook_status($statuses, $webhook) {
    if (isset($statuses['failed'])) {
        error_log('Webhook failed: ' . $webhook->get_id());
    }
}

(サンプルコードの引用元: WPBeginner)

サンプル3: 外部APIへのリクエスト送信

ウェブフックが特定の状態に変わったときに、外部APIにリクエストを送信します。

add_action('woocommerce_webhook_statuses', 'send_request_to_external_api', 10, 2);

function send_request_to_external_api($statuses, $webhook) {
    if (in_array('success', $statuses)) {
        wp_remote_post('https://api.example.com/endpoint', [
            'method' => 'POST',
            'body' => json_encode(['webhook_id' => $webhook->get_id()]),
            'headers' => ['Content-Type' => 'application/json'],
        ]);
    }
}

(サンプルコードの引用元: WooCommerce Docs)

サンプル4: ステータス変更のフィルタリング

特定の条件に基づき、ウェブフックのステータスをフィルタリングします。

add_action('woocommerce_webhook_statuses', 'filter_webhook_statuses', 10, 2);

function filter_webhook_statuses($statuses, $webhook) {
    if (!current_user_can('manage_options')) {
        unset($statuses['deprecated_status']);
    }
    return $statuses;
}

(サンプルコードの引用元: Advanced Custom Fields)

サンプル5: ステータスごとのメール通知

特定のウェブフックステータスが変更された際に、メール通知を送信します。

add_action('woocommerce_webhook_statuses', 'notify_on_webhook_status_change', 10, 2);

function notify_on_webhook_status_change($statuses, $webhook) {
    if (in_array('failed', $statuses)) {
        wp_mail('admin@example.com', 'Webhook Failed', 'The webhook has failed.');
    }
}

(サンプルコードの引用元: Kinsta)

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

アクション 使用例
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

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


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