概要
woocommerce_product_price_class
フィルタは、WooCommerceで商品価格に関連するクラス名をカスタマイズする際に使用されます。このフィルタを活用することで、特定の条件に応じて商品価格のスタイリングを変更することができます。一般的には以下のような機能の実装時に利用されます:
- 商品の販売状態に基づくスタイルの変更
- 特定のカスタム属性を持つ商品のスタイリング
- 会員ランクに応じた価格表示のカスタマイズ
- 大量購入への割引を示す特別なクラスの追加
- 商品カテゴリーに基づく異なるスタイルの適用
- エコ商品やセール商品のハイライト表示
構文
add_filter('woocommerce_product_price_class', 'your_custom_price_class_function', 10, 2);
パラメータ
$class
: 既存のクラス名。$product
: 商品オブジェクト。
戻り値
このフィルタは、カスタマイズされたクラス名の文字列を返します。
対応バージョン
- 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: 商品のセール価格に特別なクラスを追加する
このサンプルでは、商品がセール中の場合に「sale」クラスを追加します。
add_filter('woocommerce_product_price_class', 'custom_sale_price_class', 10, 2);
function custom_sale_price_class($class, $product) {
if ($product->is_on_sale()) {
$class .= ' custom-sale-price';
}
return $class;
}
引用元: https://woocommerce.com
サンプルコード2: 特定のカスタムフィールドに基づくクラスを追加
このサンプルでは、特定のカスタムフィールド「is_featured」がtrueの場合にクラスを追加します。
add_filter('woocommerce_product_price_class', 'custom_featured_price_class', 10, 2);
function custom_featured_price_class($class, $product) {
if (get_post_meta($product->get_id(), 'is_featured', true)) {
$class .= ' custom-featured-price';
}
return $class;
}
引用元: https://docs.woocommerce.com
サンプルコード3: 商品カテゴリーに応じたクラスの追加
このサンプルでは、特定のカテゴリーに属する商品の価格にカスタムクラスを追加します。
add_filter('woocommerce_product_price_class', 'custom_category_price_class', 10, 2);
function custom_category_price_class($class, $product) {
if (has_term('special-category', 'product_cat', $product->get_id())) {
$class .= ' custom-special-category';
}
return $class;
}
引用元: https://woothemes.com
サンプルコード4: 商品の在庫状況に応じたスタイルの適用
このサンプルでは、在庫が無い商品に特別なクラスを追加します。
add_filter('woocommerce_product_price_class', 'custom_out_of_stock_price_class', 10, 2);
function custom_out_of_stock_price_class($class, $product) {
if (!$product->is_in_stock()) {
$class .= ' custom-out-of-stock';
}
return $class;
}
引用元: https://woocommerce.com
サンプルコード5: カスタムロールに基づく価格クラスの変更
このサンプルでは、「premium_member」というロールが付与されたユーザーのために特別なクラスを追加します。
add_filter('woocommerce_product_price_class', 'custom_premium_member_price_class', 10, 2);
function custom_premium_member_price_class($class, $product) {
if (current_user_can('premium_member')) {
$class .= ' custom-premium';
}
return $class;
}
引用元: https://docs.woocommerce.com