概要
フィルタ woocommerce_default_order_status
は、WooCommerce の新しい注文が作成された際のデフォルトの注文ステータスを変更するために使用されます。このフィルタを使うことで、特定の条件に基づいてデフォルトのステータスをカスタマイズし、注文フローやビジネス要件に合わせた処理を柔軟に管理できます。よく使われる機能には以下のようなものがあります。
- 注文ステータスを特定の値(例:
completed
)に設定する。 - 新しい注文がトリガーになって異なるロジックを実行(例:通知の送信)。
- 特定の条件下で注文のデフォルトステータスを変更(例:会員限定特典)。
- 過去の注文データに基づいてデフォルトステータスを動的に調整。
- サードパーティのサービスと連携するためにステータスを変更。
- テスト環境と本番環境での異なるデフォルトステータスの設定。
構文
add_filter('woocommerce_default_order_status', 'custom_default_order_status');
function custom_default_order_status($status) {
return 'on-hold'; // 新しいデフォルトステータスとして'on-hold'を返す
}
パラメータ
$status
(string) : 現在のデフォルトの注文ステータス
戻り値
- (string) : 新しいデフォルトの注文ステータス
対応する WooCommerce のバージョン
- WooCommerce 2.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: デフォルトの注文ステータスを「processing」に変更
新しい注文が作成されたときに、そのステータスを「processing」に設定します。
add_filter('woocommerce_default_order_status', function($status) {
return 'processing';
});
引用元: https://www.example.com
サンプルコード2: 特定のユーザーがログインしているときのデフォルトステータス変更
特定のユーザーがログインしている場合、新しい注文のデフォルトステータスを「completed」に変更します。
add_filter('woocommerce_default_order_status', function($status) {
if (is_user_logged_in() && current_user_can('specific_role')) {
return 'completed';
}
return $status;
});
引用元: https://www.example.com
サンプルコード3: 古い注文データに基づく条件付き変更
最近の注文に基づいてデフォルト注文ステータスを調整します。
add_filter('woocommerce_default_order_status', function($status) {
$recent_orders = wc_get_orders(array('limit' => 1, 'orderby' => 'date', 'order' => 'DESC'));
if (!empty($recent_orders)) {
return 'on-hold';
}
return $status;
});
引用元: https://www.example.com
サンプルコード4: 未来のリリースに合わせたステータス設定
特定のフューチャーリリースに備えてデフォルトの注文ステータスを設定します。
add_filter('woocommerce_default_order_status', function($status) {
$release_date = strtotime('2024-01-01');
if (time() < $release_date) {
return 'pending';
}
return $status;
});
引用元: https://www.example.com
サンプルコード5: カスタムフィールドによる条件付き設定
特定のカスタムフィールドが設定されている場合、デフォルトの注文ステータスを「completed」に変更します。
add_filter('woocommerce_default_order_status', function($status) {
$custom_field_value = get_option('custom_field_name');
if ($custom_field_value === 'enable') {
return 'completed';
}
return $status;
});
引用元: https://www.example.com