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

概要

woocommerce_payment_complete_order_status フィルタは、WooCommerce内での決済完了時に注文ステータスを変更するために使用されます。このフィルタは、カスタムステータスを適用したり、特定の条件に基づいて異なる付与を行いたい場合に便利です。一般的な用途としては以下のようなものがあります。

  1. 利用者ごとに特定のオーダーの状態を変更する。
  2. 特定の決済手段に応じて注文ステータスを制御する。
  3. アフィリエイトプログラムを導入する際、特定の条件でステータスを調整する。
  4. ショッピングカートにアイテムが追加された後に自動的にオーダーステータスを変更する。
  5. 在庫管理の自動化のために注文ステータスをカスタマイズする。
  6. トランザクションの種類に基づいて異なるフローを実装する。

構文

add_filter('woocommerce_payment_complete_order_status', 'your_custom_function', 10, 2);

パラメータ

  • $status (string): 現在の注文ステータス。
  • $order_id (int): 完了した注文のID。

戻り値

  • (string): 修正したい注文ステータス。

WooCommerceとWordPressのバージョン

  • WooCommerce: 2.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_complete_order_status', 'set_order_status_to_completed', 10, 2);
function set_order_status_to_completed($status, $order_id) {
    return 'completed';
}

このコードは、すべての決済完了時に注文のステータスを「completed」に固定します。

サンプルコード2: 特定の決済方法に基づくステータス変更

add_filter('woocommerce_payment_complete_order_status', 'conditional_order_status', 10, 2);
function conditional_order_status($status, $order_id) {
    $order = wc_get_order($order_id);
    if ($order->get_payment_method() == 'cod') {
        return 'processing'; // 代金引換の場合、処理中に設定する
    }
    return $status;
}

このコードは、代金引換決済が選ばれた場合に注文ステータスを「processing」に変更します。

サンプルコード3: 商品の種類に基づくステータス変更

add_filter('woocommerce_payment_complete_order_status', 'set_status_based_on_product', 10, 2);
function set_status_based_on_product($status, $order_id) {
    $order = wc_get_order($order_id);
    foreach ($order->get_items() as $item) {
        if ($item->get_product_id() == 123) { // 特定の商品の場合
            return 'on-hold'; // ステータスを「on-hold」に設定する
        }
    }
    return $status;
}

このコードは、特定の商品が含まれている場合にステータスを「on-hold」に変更します。

サンプルコード4: カスタムステータスの適用

add_filter('woocommerce_payment_complete_order_status', 'apply_custom_order_status', 10, 2);
function apply_custom_order_status($status, $order_id) {
    if (get_post_meta($order_id, '_is_custom_status', true)) {
        return 'custom_status'; // カスタムステータスを適用
    }
    return $status;
}

このコードは、カスタムメタデータが存在する場合にカスタムステータスを適用します。

サンプルコード5: スマートフォンからのアクセス時のステータス変更

add_filter('woocommerce_payment_complete_order_status', 'mobile_order_status', 10, 2);
function mobile_order_status($status, $order_id) {
    if (wp_is_mobile()) {
        return 'failed'; // スマートフォンからの決済が失敗として扱われる
    }
    return $status;
}

このコードは、スマートフォン経由で注文が行われた場合、ステータスを「failed」に設定します。

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


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