概要
woocommerce_format_price_range
関数は、WooCommerceで商品価格のレンジをフォーマットするために使用されます。この関数は、特に商品の販売価格が異なる範囲を示す必要がある場合に便利です。以下のような機能を実装する際によく使われます。
- 商品の価格帯を表示する。
- バリエーション商品の価格を表示する。
- セール特価の価格範囲を表示する。
- 絞り込み検索機能で価格をフィルタリングする。
- カテゴリーページで価格範囲を表示する。
- 顧客のために比較価格を見せる。
構文
woocommerce_format_price_range( $min_price, $max_price, $currency_symbol );
パラメータ
$min_price
(float): 最小価格$max_price
(float): 最大価格$currency_symbol
(string): 通貨記号(オプション)
戻り値
- 価格範囲を表す文字列。例: “¥10,000 – ¥15,000”
使用可能なプラグインのバージョン
- WooCommerce: 3.0.0以降
- WordPress: 4.0以降
サンプルコード
サンプルコード1
$min_price = 1000;
$max_price = 5000;
$formatted_price_range = woocommerce_format_price_range( $min_price, $max_price, get_woocommerce_currency_symbol() );
echo $formatted_price_range; // 結果: "¥1,000 - ¥5,000"
このコードは、指定した最小価格と最大価格をウェブサイト上でフォーマットして表示します。
サンプルコード2
function display_price_range_for_product( $product_id ) {
$product = wc_get_product( $product_id );
if ( $product->is_type( 'variable' ) ) {
$min_price = $product->get_variation_price( 'min' );
$max_price = $product->get_variation_price( 'max' );
return woocommerce_format_price_range( $min_price, $max_price, get_woocommerce_currency_symbol() );
}
return '';
}
このコードは、バリエーション商品に対して価格範囲を表示する関数です。
サンプルコード3
$products = wc_get_products( array('limit' => -1) );
foreach ( $products as $product ) {
$price_range = woocommerce_format_price_range( $product->get_regular_price(), $product->get_sale_price(), get_woocommerce_currency_symbol() );
echo "<div>{$product->get_name()}: {$price_range}</div>";
}
このコードは、全商品に対して価格範囲を取得し、商品名と一緒に表示します。
サンプルコード4
function custom_price_range_shortcode() {
global $product;
if ( $product ) {
$min_price = $product->get_regular_price();
$max_price = $product->get_sale_price();
return woocommerce_format_price_range( $min_price, $max_price, get_woocommerce_currency_symbol() );
}
}
add_shortcode( 'price_range', 'custom_price_range_shortcode' );
このコードは、ショートコードを使って価格範囲を表示する機能を実装しています。
サンプルコード5
$product_id = 123; // 任意の製品ID
$min_price = get_post_meta( $product_id, '_min_price', true );
$max_price = get_post_meta( $product_id, '_max_price', true );
echo woocommerce_format_price_range( $min_price, $max_price, get_woocommerce_currency_symbol() );
このコードは、特定の製品IDから最小価格と最大価格を取得し、それらをフォーマットして表示します。
この関数のアクションでの使用可能性
アクション | 使用可能 |
---|---|
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 |