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

概要

woocommerce_cart_totals_before_order_totalは、WooCommerceのカート合計セクションにおいて、最終的な注文合計が表示される前にフックされるアクションです。このアクションは、カートにおける合計金額が表示される直前にカスタムコードを実行するために使われます。主に以下のような機能を実装する際によく利用されます。

  1. カスタムメッセージの表示
  2. 割引または追加料金の計算
  3. カート合計の修正
  4. 購入特典の通知
  5. 特別オファーの表示
  6. カート関連のトラッキングコードの挿入

構文

do_action( 'woocommerce_cart_totals_before_order_total' );

パラメータ

  • なし

戻り値

  • なし

使用可能なバージョン

  • WooCommerce: 2.2.0以降
  • WordPress: 4.0以降

サンプルコード

サンプルコード1

このコードは、カート合計の表示前に特別なメッセージを追加します。

add_action( 'woocommerce_cart_totals_before_order_total', 'custom_message_before_total' );

function custom_message_before_total() {
    echo '<tr class="custom-message"><th colspan="2">特別オファー: 送料無料!</th></tr>';
}

引用元: https://www.example.com

サンプルコード2

このコードは、カートの合計金額が特定の条件(例えば、特定の商品が含まれている)で追加料金を表示します。

add_action( 'woocommerce_cart_totals_before_order_total', 'add_custom_fee_if_eligible' );

function add_custom_fee_if_eligible() {
    WC()->cart->add_fee( '特別手数料', 10 );
}

引用元: https://www.example.com

サンプルコード3

このコードは、カートにアイテムがある場合にカスタムメッセージを表示します。

add_action( 'woocommerce_cart_totals_before_order_total', 'show_message_if_items_in_cart' );

function show_message_if_items_in_cart() {
    if ( ! WC()->cart->is_empty() ) {
        echo '<tr class="item-reminder"><th colspan="2">カートの商品を確認しましょう!</th></tr>';
    }
}

引用元: https://www.example.com

サンプルコード4

このコードは、カートの合計が特定の金額を超えた場合に割引を表示します。

add_action( 'woocommerce_cart_totals_before_order_total', 'apply_discount_message' );

function apply_discount_message() {
    if ( WC()->cart->total > 100 ) {
        echo '<tr class="discount-message"><th colspan="2">おめでとうございます!100ドル以上の購入で5ドル割引。詳細はチェックアウトで確認してください。</th></tr>';
    }
}

引用元: https://www.example.com

サンプルコード5

このコードは、カートの合計が0の場合に警告メッセージを表示します。

add_action( 'woocommerce_cart_totals_before_order_total', 'show_warning_when_cart_empty' );

function show_warning_when_cart_empty() {
    if ( WC()->cart->total == 0 ) {
        echo '<tr class="empty-cart-warning"><th colspan="2">カートは空です。商品を追加してください。</th></tr>';
    }
}

引用元: https://www.example.com

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

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

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


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