概要
woocommerce_cart_contents_total
フィルタは、WooCommerceでショッピングカート内の商品合計金額を変更するために使用されます。主に、表示されるカート合計をカスタマイズしたい場合や、特定の条件に基づいて価格を調整する場合に使用されます。このフィルタは、さまざまな機能の実装に役立ちます。例えば:
- 割引を適用する
- 課税を計算する
- 特定の商品カテゴリーに対して特別価格を設定する
- クーポンコードによる価格変更
- 外部APIからの価格情報を統合する
- 通常のカート計算をカスタマイズする
フィルタの概要
- 構文:
add_filter( 'woocommerce_cart_contents_total', 'your_function_name', 10, 2 );
- パラメータ:
$cart_total
(float): カートの合計金額$cart
(WC_Cart): WooCommerceのカートオブジェクト
- 戻り値: 変更されたカート合計金額 (float)
- WooCommerceのバージョン: 3.0.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: カート合計に10%割引を適用
add_filter( 'woocommerce_cart_contents_total', 'apply_discount_to_cart_total', 10, 2 );
function apply_discount_to_cart_total( $cart_total, $cart ) {
$discount = $cart_total * 0.10; // 10%の割引
return $cart_total - $discount; // 割引後の金額を返す
}
このコードは、カートの合計金額から10%の割引を適用します。
サンプル2: 特定の商品に対する追加料金を追加
add_filter( 'woocommerce_cart_contents_total', 'add_surcharge_for_special_item', 10, 2 );
function add_surcharge_for_special_item( $cart_total, $cart ) {
foreach ( $cart->get_cart() as $cart_item ) {
if ( $cart_item['product_id'] == 123 ) { // 商品ID123に追加料金を適用
$cart_total += 5; // 追加料金5ドル
}
}
return $cart_total;
}
このコードは、特定の商品に対して5ドルの追加料金を加えます。
サンプル3: カート合計を特定のカテゴリに基づいて調整
add_filter( 'woocommerce_cart_contents_total', 'adjust_total_for_category', 10, 2 );
function adjust_total_for_category( $cart_total, $cart ) {
$has_special_category = false;
foreach ( $cart->get_cart() as $cart_item ) {
if ( has_term( 'special-category', 'product_cat', $cart_item['product_id'] ) ) {
$has_special_category = true;
break;
}
}
if ( $has_special_category ) {
return $cart_total * 0.95; // 5%割引
}
return $cart_total;
}
このコードは、特定のカテゴリの商品がカートに含まれている場合に5%の割引を適用します。
サンプル4: カートが$100以上の場合は追加の割引を提供
add_filter( 'woocommerce_cart_contents_total', 'additional_discount_for_large_orders', 10, 2 );
function additional_discount_for_large_orders( $cart_total, $cart ) {
if ( $cart_total > 100 ) {
return $cart_total - 10; // $10のディスカウント
}
return $cart_total;
}
このコードは、カートの合計が$100を超える場合に$10の割引を提供します。
サンプル5: ユーザーがログインしている場合にボーナスを提供
add_filter( 'woocommerce_cart_contents_total', 'bonus_for_logged_in_users', 10, 2 );
function bonus_for_logged_in_users( $cart_total, $cart ) {
if ( is_user_logged_in() ) {
return $cart_total - 2; // ログインユーザーに$2のボーナスを提供
}
return $cart_total;
}
このコードは、ユーザーがログインしている場合にカートの合計から$2を差し引きます。
引用元は特にありませんが、これらのサンプルはWooCommerceの公式ドキュメントや一般的な開発者フォーラムに基づいています。