概要
woocommerce_get_order_item_totals
フィルタは、WooCommerce の注文アイテムの合計金額にカスタマイズを加える際に使用されます。このフックを利用することで、以下のような機能を実装することができます。
- 合計金額の項目をカスタマイズする
- 新しい合計金額の項目を追加する
- 既存の合計金額の項目を削除する
- 合計金額のフォーマットを変更する
- 特定の条件に基づいて合計金額を変更する
- 購入者に表示する情報をカスタマイズする
構文
apply_filters( 'woocommerce_get_order_item_totals', $total_rows, $order, $tax_display );
パラメータ
$total_rows
:表示される合計金額の配列。$order
:対象の注文オブジェクト。$tax_display
:税金表示のオプション。
戻り値
- カスタマイズされた合計金額の配列。
WooCommerceおよびWordPressのバージョン
- 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: 新しい合計欄の追加
このコードは、注文合計に新しい項目「ギフトラッピング」を追加します。
add_filter('woocommerce_get_order_item_totals', 'add_gift_wrapping_total', 10, 3);
function add_gift_wrapping_total($total_rows, $order, $tax_display) {
$gift_wrapping = 5.00; // ギフトラッピングの金額
$total_rows['gift_wrapping'] = array(
'label' => __('Gift Wrapping', 'woocommerce'),
'value' => wc_price($gift_wrapping),
);
return $total_rows;
}
サンプルコード2: 合計項目のラベルをカスタマイズ
これは「送料」の項目名を「配送料」に変更するコードです。
add_filter('woocommerce_get_order_item_totals', 'customize_shipping_label', 10, 3);
function customize_shipping_label($total_rows, $order, $tax_display) {
if (isset($total_rows['shipping'])) {
$total_rows['shipping']['label'] = __('配送料', 'woocommerce');
}
return $total_rows;
}
サンプルコード3: 合計金額の表示を変更
このコードは、合計金額に税金を加算したものを表示します。
add_filter('woocommerce_get_order_item_totals', 'modify_order_total_with_tax', 10, 3);
function modify_order_total_with_tax($total_rows, $order, $tax_display) {
$total = $order->get_total() + $order->get_total_tax();
$total_rows['total'] = array(
'label' => __('Total with Tax', 'woocommerce'),
'value' => wc_price($total),
);
return $total_rows;
}
サンプルコード4: 特定の条件で金額を減算
このコードは、特定の製品が含まれている場合、合計金額から割引を適用します。
add_filter('woocommerce_get_order_item_totals', 'apply_discount_if_product_exists', 10, 3);
function apply_discount_if_product_exists($total_rows, $order, $tax_display) {
$has_discount_product = false;
foreach ($order->get_items() as $item_id => $item) {
if ($item->get_product_id() == 123) { // 商品ID 123 の場合
$has_discount_product = true;
break;
}
}
if ($has_discount_product) {
$discount = 10.00; // 割引額
$total_rows['discount'] = array(
'label' => __('Discount', 'woocommerce'),
'value' => '-' . wc_price($discount),
);
}
return $total_rows;
}
サンプルコード5: 特殊なフォーマットを適用
このコードは合計金額のフォーマットを変更します。
add_filter('woocommerce_get_order_item_totals', 'change_total_format', 10, 3);
function change_total_format($total_rows, $order, $tax_display) {
$total_rows['total']['value'] = str_replace('¥', 'JPY ', $total_rows['total']['value']); // 通貨の表記を変更
return $total_rows;
}
これらのサンプルコードは、WooCommerceの注文合計に関するさまざまなカスタマイズを示しており、開発者が特定のニーズに応じてカスタマイズする助けになります。