概要
woocommerce_before_calculate_totals
は、WooCommerceのカートの合計金額を計算する前にフックされるアクションです。このアクションは、カート内の商品の合計金額が計算される直前に実行されるため、カートアイテムに対する操作を行う際に非常に便利です。よく実装される機能には、次のようなものがあります。
- カスタム料金の追加
- 割引の適用
- 特典・クーポンの計算
- 商品の価格修正
- 在庫レベルに応じた料金の変更
- 商品の税率の調整
構文
add_action( 'woocommerce_before_calculate_totals', 'function_name' );
パラメータ
woocommerce_before_calculate_totals
では、特にパラメータはありませんが、カート内のアイテムのオブジェクトを操作できます。
戻り値
このアクションは、特定の値を返さないため、戻り値はありません。
使用可能なプラグインWooCommerceのバージョン
このアクションは、WooCommerceのバージョン3.0以降で使用可能です。
使用可能なWordPressのバージョン
WordPressバージョン4.0以降で使用可能です。
サンプルコード
サンプルコード1: 商品のカスタム料金を追加
add_action( 'woocommerce_before_calculate_totals', 'add_custom_fee' );
function add_custom_fee( $cart ) {
if ( ! is_admin() && ! defined( 'DOING_AJAX' ) ) {
$cart->add_fee( 'カスタム料金', 10 );
}
}
このコードは、カートの合計金額を計算する前に、10ドルのカスタム料金を加えます。
サンプルコード2: 割引の適用
add_action( 'woocommerce_before_calculate_totals', 'apply_cart_discount' );
function apply_cart_discount( $cart ) {
$discount = 5; // 割引額
if ( ! is_admin() && ! defined( 'DOING_AJAX' ) ) {
$cart->add_fee( '割引', -$discount );
}
}
このコードは、カートの合計に5ドルの割引を適用します。
サンプルコード3: 商品の価格を動的に修正
add_action( 'woocommerce_before_calculate_totals', 'modify_product_prices' );
function modify_product_prices( $cart ) {
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_price( 20 ); // 価格を20に設定
}
}
このコードは、カート内のすべての商品の価格を20ドルに変更します。
サンプルコード4: 在庫レベルに応じた料金の変更
add_action( 'woocommerce_before_calculate_totals', 'adjust_fee_based_on_stock' );
function adjust_fee_based_on_stock( $cart ) {
$product_id = 123; // 対象商品ID
$product = wc_get_product( $product_id );
if ( $product->get_stock_quantity() < 5 ) {
$cart->add_fee( '在庫不足料金', 15 );
}
}
このコードは、特定の商品が5個未満の在庫の場合、15ドルの料金を加えます。
サンプルコード5: 税率の調整
add_action( 'woocommerce_before_calculate_totals', 'adjust_tax_rate' );
function adjust_tax_rate( $cart ) {
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item['data']->set_tax_class(' reduced-rate'); // 税率を調整
}
}
このコードは、カート内の商品の税率を特定の税クラスに変更します。
この関数のアクションでの使用可能性
アクション名 | 使用例 |
---|---|
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 |