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

概要

woocommerce_get_cancel_order_url_rawフィルタは、WooCommerceにおいて注文のキャンセルURLを取得する際に使用されるフィルタです。このフィルタを利用することで、キャンセルURLを動的に変更したり、特定の条件に応じて異なるURLを返したりすることができます。このフィルタは、特に以下のような機能の実装に役立ちます。

  1. キャンセルURLのカスタマイズ
  2. セキュリティ要件に基づくURLの変更
  3. 条件に応じたリダイレクト先の変更
  4. 組み込みのフレームワークやライブラリとの連携
  5. ユーザーエクスペリエンス向上のためのキャンセル動作の調整
  6. キャンセル後のトラッキング用URLの追加

構文

add_filter( 'woocommerce_get_cancel_order_url_raw', 'your_function_name', 10, 2 );

パラメータ

  • $cancel_url_raw (string): デフォルトのキャンセルURL。
  • $order (WC_Order): 現在の注文オブジェクト。

戻り値

このフィルタは、キャンセルのためのURLを返します。

対応しているバージョン

  • WooCommerce: 3.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: URLにクエリパラメータを追加

このサンプルコードでは、キャンセルURLに特定のクエリパラメータを追加しています。

add_filter( 'woocommerce_get_cancel_order_url_raw', 'add_query_param_to_cancel_url', 10, 2 );

function add_query_param_to_cancel_url( $cancel_url_raw, $order ) {
    return $cancel_url_raw . '?source=custom';
}

(引用元: https://example.com/sample1)

サンプルコード2: 特定の条件によりURLを変更

このサンプルコードでは、特定のユーザーのキャンセルURLを変更しています。

add_filter( 'woocommerce_get_cancel_order_url_raw', 'conditional_cancel_url', 10, 2 );

function conditional_cancel_url( $cancel_url_raw, $order ) {
    if ( $order->get_user_id() === 42 ) {
        return 'https://example.com/custom-cancel-url';
    }
    return $cancel_url_raw;
}

(引用元: https://example.com/sample2)

サンプルコード3: 落ち着いたリダイレクト

このサンプルコードは、キャンセルが発生した際にユーザーを特定のページにリダイレクトします。

add_filter( 'woocommerce_get_cancel_order_url_raw', 'redirect_after_cancel', 10, 2 );

function redirect_after_cancel( $cancel_url_raw, $order ) {
    return home_url( '/thank-you' );
}

(引用元: https://example.com/sample3)

サンプルコード4: カスタムメッセージの付加

このサンプルコードでは、キャンセルリンクにカスタムメッセージを追加しています。

add_filter( 'woocommerce_get_cancel_order_url_raw', 'add_cancel_message', 10, 2 );

function add_cancel_message( $cancel_url_raw, $order ) {
    return $cancel_url_raw . '#message=Your+order+has+been+cancelled.';
}

(引用元: https://example.com/sample4)

サンプルコード5: 特定の日付にのみ有効なキャンセルURL

このサンプルコードでは、特定の日付にのみ有効なキャンセルURLを返します。

add_filter( 'woocommerce_get_cancel_order_url_raw', 'date_specific_cancel_url', 10, 2 );

function date_specific_cancel_url( $cancel_url_raw, $order ) {
    if ( current_time( 'Y-m-d' ) === '2024-01-01' ) {
        return 'https://example.com/special-cancel';
    }
    return $cancel_url_raw;
}

(引用元: https://example.com/sample5)

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


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