プラグインWooCommerceのwoocommerce_get_price_html_from_toフィルタの使用方法・解説

概要

woocommerce_get_price_html_from_to フィルタは、WooCommerceプラグインにおいて、商品の価格表示に関するカスタマイズを行うためのフックです。このフィルタを使用することで、特定の条件に応じた価格情報を柔軟に変更できます。主に以下の機能を実装する際に利用されます。

  1. 価格範囲の書式をカスタマイズする
  2. 割引情報を追加表示する
  3. 通常価格とセール価格を異なるスタイルで表示する
  4. カスタムクッキーメッセージを価格の横に追加する
  5. 特定の商品カテゴリだけに適用するフォーマッティングを設定する
  6. 多言語対応の価格表記を実装する

フィルタの概要

  • 構文: add_filter( 'woocommerce_get_price_html_from_to', 'your_function_name', 10, 2 );
  • パラメータ:
    • $price_html: 価格のHTML
    • $product: 商品オブジェクト
  • 戻り値: 修正された価格のHTML
  • 使用可能なプラグインWooCommerceのバージョン: 4.0 以降
  • ワードプレスのバージョン: 5.0 以降

サンプルコード

サンプル1: 価格範囲のカスタマイズ

このコードは、商品の価格範囲をカスタムフォーマットで表示するためのものです。

add_filter( 'woocommerce_get_price_html_from_to', 'custom_price_range_format', 10, 2 );

function custom_price_range_format( $price_html, $product ) {
    if ( $product->is_on_sale() ) {
        $price_html = '<strong>特別価格:</strong> ' . $price_html;
    }
    return $price_html;
}

サンプル2: 通常価格とセール価格のスタイル変更

通常価格とセール価格を異なるCSSクラスで表示します。

add_filter( 'woocommerce_get_price_html_from_to', 'style_price_labels', 10, 2 );

function style_price_labels( $price_html, $product ) {
    if ( $product->is_on_sale() ) {
        $price_html = '<span class="regular-price">' . $product->get_regular_price() . '</span> <span class="sale-price">' . $product->get_sale_price() . '</span>';
    }
    return $price_html;
}

サンプル3: 割引メッセージの追加

価格表示に割引メッセージを追加します。

add_filter( 'woocommerce_get_price_html_from_to', 'add_discount_message', 10, 2 );

function add_discount_message( $price_html, $product ) {
    if ( $product->is_on_sale() ) {
        $discount_percentage = round( ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100 );
        $price_html .= ' <span class="discount">(' . $discount_percentage . '% OFF)</span>';
    }
    return $price_html;
}

サンプル4: クッキーメッセージの追加

特定のクッキーが設定されている場合に、価格表示の横にメッセージを追加します。

add_filter( 'woocommerce_get_price_html_from_to', 'append_cookie_message', 10, 2 );

function append_cookie_message( $price_html, $product ) {
    if ( isset( $_COOKIE['special_offer'] ) ) {
        $price_html .= ' <span class="cookie-message">特別オファー適用中</span>';
    }
    return $price_html;
}

サンプル5: 商品カテゴリによる適用

特定のカテゴリの商品にのみ適用するカスタマイズを行います。

add_filter( 'woocommerce_get_price_html_from_to', 'category_specific_price_format', 10, 2 );

function category_specific_price_format( $price_html, $product ) {
    if ( has_term( '特価', 'product_cat', $product->get_id() ) ) {
        $price_html = '<span class="special-category-price">' . $price_html . '</span>';
    }
    return $price_html;
}

この関数のアクションでの使用可能性

アクション 使用可能性
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

この関数について質問する


上の計算式の答えを入力してください