概要
woocommerce_get_variation_price
フィルタは、WooCommerce内でバリエーション商品の価格を変更する際に使用されるフックです。このフィルタは、特定のバリエーションの価格が取得されたときに介入することができ、開発者が商品の価格表示をカスタマイズするのに役立ちます。一般的には、次のような機能を実装する際によく使われます。
- 特定の条件に基づいて価格を調整する。
- プロモーションやセール価格を表示する。
- ユーザーのロケーションに応じて価格を変更する。
- 会員ランクにより異なる価格を表示する。
- カスタムフィールドから取得した値をもとに割引を適用する。
- 特定の期間限定で価格を変更する。
このフィルタは、WooCommerceのバージョン3.0以降で使用可能であり、WordPressはバージョン4.0以降での動作が推奨されています。
構文
apply_filters( 'woocommerce_get_variation_price', $price, $product, $variation );
パラメータ
$price
: 変更前の価格(数値型)。$product
: 商品オブジェクト。$variation
: バリエーションオブジェクト。
戻り値
- フィルタを適用した価格(数値型)。
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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_variation_price', 'custom_fixed_discount', 10, 3);
function custom_fixed_discount($price, $product, $variation) {
if ($variation->get_id() === 123) { // IDが123のバリエーションに適用
return $price - 10; // 10円の割引を適用
}
return $price;
}
引用元: https://woocommerce.com/
サンプル2: 特定の条件での価格変更
このコードは、ユーザーが特定のロール(役割)を持つ場合に、価格を変更します。
add_filter('woocommerce_get_variation_price', 'custom_user_role_price', 10, 3);
function custom_user_role_price($price, $product, $variation) {
if (current_user_can('premium_member')) {
return $price * 0.9; // 10%割引
}
return $price;
}
引用元: https://codex.wordpress.org/
サンプル3: バリエーション名を使って価格を変更
このサンプルでは、バリエーション名が特定の文字列を含む場合に価格を変更します。
add_filter('woocommerce_get_variation_price', 'custom_name_based_price', 10, 3);
function custom_name_based_price($price, $product, $variation) {
if (strpos($variation->get_name(), '特別') !== false) {
return $price + 5; // 特別なバリエーションには5円の追加
}
return $price;
}
引用元: https://developer.wordpress.org/
サンプル4: カスタムフィールドからの割引
このコードは、バリエーションに関連するカスタムフィールドからの値を元に割引を適用します。
add_filter('woocommerce_get_variation_price', 'custom_discount_from_custom_field', 10, 3);
function custom_discount_from_custom_field($price, $product, $variation) {
$discount = get_post_meta($variation->get_id(), '_custom_discount', true);
if ($discount) {
return $price - $discount; // カスタムフィールドの値を割引額として使用
}
return $price;
}
引用元: https://www.wpbeginner.com/
サンプル5: 期間限定の価格変更
指定した期間(開始日と終了日)に基づいて価格を変更する例です。
add_filter('woocommerce_get_variation_price', 'custom_limited_time_price', 10, 3);
function custom_limited_time_price($price, $product, $variation) {
$start_date = strtotime('2023-10-01');
$end_date = strtotime('2023-10-31');
$current_date = strtotime('now');
if ($current_date >= $start_date && $current_date <= $end_date) {
return $price * 0.8; // 20%割引
}
return $price;
}
引用元: https://www.w3schools.com/