概要
woocommerce_widget_shopping_cart_total
フィルタは、WooCommerceのウィジェットで表示されるショッピングカートの合計金額をカスタマイズするために使用されます。このフィルタを活用することで、ショッピングカートの合計金額を計算して返す値を変更することができます。一般的には、以下のような機能を実装する際に役立ちます。
- 個別の商品に割引やプロモーションを適用した合計金額の表示
- 特定の条件に基づいた税金の計算
- 買い物カートの金額を独自のフォーマットで表示
- 合計金額にカスタム手数料を加算する
- 定期課金やサブスクリプションの合計金額を表示
- カート合計を外部のサービスやAPIから取得したデータに基づいて調整
構文
add_filter('woocommerce_widget_shopping_cart_total', 'custom_widget_shopping_cart_total', 10, 2);
パラメータ
woocommerce_widget_shopping_cart_total
: フィルタの名前custom_widget_shopping_cart_total
: カスタマイズする関数名10
: 優先順位(デフォルト)2
: 引数の数(合計金額, カート)
戻り値
フィルタを通じて返されるのは、カスタマイズされたカートの合計金額。
使用可能なプラグインWooCommerceのバージョン
WooCommerceのバージョンは1.6以降で使用可能。
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
add_filter('woocommerce_widget_shopping_cart_total', 'custom_discounted_cart_total', 10, 2);
function custom_discounted_cart_total($cart_total, $cart) {
$discount = 5; // 固定割引額
$new_total = $cart_total - $discount;
return $new_total < 0 ? 0 : $new_total; // 最小0
}
このサンプルコードは、ショッピングカートの合計金額から固定の割引を適用します。
サンプルコード2
add_filter('woocommerce_widget_shopping_cart_total', 'custom_tax_calculation', 10, 2);
function custom_tax_calculation($cart_total, $cart) {
$tax_rate = 0.1; // 10%の税率
$tax_amount = $cart_total * $tax_rate;
return $cart_total + $tax_amount;
}
このサンプルコードでは、カートの合計に税金を追加した金額を返します。
サンプルコード3
add_filter('woocommerce_widget_shopping_cart_total', 'custom_cart_total_format', 10, 2);
function custom_cart_total_format($cart_total, $cart) {
return '合計: ¥' . number_format($cart_total, 0); // フォーマットを変更
}
このサンプルコードは、カートの合計金額をカスタムフォーマットで表示します。
サンプルコード4
add_filter('woocommerce_widget_shopping_cart_total', 'add_custom_fee_to_cart_total', 10, 2);
function add_custom_fee_to_cart_total($cart_total, $cart) {
$custom_fee = 2; // 固定手数料
return $cart_total + $custom_fee; // 手数料を合計に追加
}
このサンプルコードでは、指定した手数料をカートの合計に追加します。
サンプルコード5
add_filter('woocommerce_widget_shopping_cart_total', 'update_cart_total_for_subscription', 10, 2);
function update_cart_total_for_subscription($cart_total, $cart) {
if (is_user_logged_in() && is_subscription_active()) {
$discount = 3; // サブスクリプション割引
return $cart_total - $discount;
}
return $cart_total;
}
このサンプルコードは、ユーザーがログインしておりアクティブなサブスクリプションを持っている場合に、カートの総額から割引を適用します。