概要
woocommerce_cart_item_subtotal
フィルタは、WooCommerceのカート内のアイテムの小計を変更するために使用されます。このフィルタは、さまざまな用途で使用でき、特にカスタマイズした価格表示や特別な割引を適用する際に重宝します。以下は、主な使用事例の一覧です。
- 商品小計にカスタム税込み価格を追加する
- 特定の条件に基づいてカート内の商品の小計を変更する
- 通常価格とセール価格の表示を調整する
- 特別割引やプロモーション情報を表示する
- 商品ごとに異なる通貨形式を適用する
- カート内商品の小計にテキスト注釈を追加する
構文
add_filter('woocommerce_cart_item_subtotal', 'custom_cart_item_subtotal', 10, 3);
パラメータ
$subtotal
(string): カートアイテムの小計 (料金部分)$cart_item
(array): カートアイテムの詳細情報$cart_item_key
(string): カートアイテムのユニークキー
戻り値
フィルタを通過した後の新しい小計の値(string)
必要要件
- WooCommerceバージョン: すべてのバージョン
- WordPressバージョン: すべてのバージョン
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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_cart_item_subtotal', 'show_tax_included_subtotal', 10, 3);
function show_tax_included_subtotal($subtotal, $cart_item, $cart_item_key) {
$taxes = WC()->cart->get_taxes_total();
return wc_price($subtotal + $taxes) . ' (税込)';
}
このコードは、カート内の商品の小計に税金を含めた価格を表示します。
サンプル2: 特定の条件に基づいて価格を変更する
add_filter('woocommerce_cart_item_subtotal', 'conditional_price_adjustment', 10, 3);
function conditional_price_adjustment($subtotal, $cart_item, $cart_item_key) {
if ($cart_item['product_id'] == 123) { // 商品IDを指定
return wc_price($subtotal * 0.9); // 10%割引を適用
}
return $subtotal;
}
このコードは、特定の商品IDに対して10%の割引を適用します。
サンプル3: カート内の商品の小計にメッセージを追加する
add_filter('woocommerce_cart_item_subtotal', 'add_custom_message_to_subtotal', 10, 3);
function add_custom_message_to_subtotal($subtotal, $cart_item, $cart_item_key) {
return $subtotal . ' - 購入でポイントが貯まります';
}
このコードは、カート内の小計の後にカスタムメッセージを追加します。
サンプル4: 英国ポンドの表示に変更する
add_filter('woocommerce_cart_item_subtotal', 'change_currency_format', 10, 3);
function change_currency_format($subtotal, $cart_item, $cart_item_key) {
return '£' . number_format($subtotal, 2);
}
このコードは、小計の表示を英国ポンド形式に変更します。
サンプル5: カスタマイズされた料金フォーマットを適用する
add_filter('woocommerce_cart_item_subtotal', 'custom_price_formatting', 10, 3);
function custom_price_formatting($subtotal, $cart_item, $cart_item_key) {
return sprintf('価格: %s', $subtotal);
}
このコードは、小計の前に「価格:」というテキストを追加して表示します。
これらのサンプルコードはすべて著作権フリーのものです。演示用として使用できますが、実際の操作時はWooCommerceのドキュメントを参考にしてください。