概要
woocommerce_product_is_on_sale
フィルタは、WooCommerceの商品がセール中かどうかを判断するために使用されます。主に、商品が割引価格で販売されているかを確認する際に便利です。このフィルタは、カスタムセールガイドや特別割引のロジックを追加する際にも多く使用されます。
よく使われる機能
- 特定の条件に基づいたセール商品リストのフィルタリング
- 商品の表示条件をカスタマイズするためのカスタムロジックの追加
- セール商品のバッジやマークの表示制御
- 商品のカスタム属性に基づいた動的なセール価格の適用
- プロモーションやクーポンに関連した複雑な割引ロジック
- カート内の商品がセール中かどうかの判断
構文
add_filter( 'woocommerce_product_is_on_sale', 'my_custom_sale_filter', 10, 2 );
パラメータ
bool $on_sale
– 商品がセール中であるかの初期値(trueまたはfalse)。WC_Product $product
– 対象となる商品オブジェクト。
戻り値
bool
– セール中である場合はtrue
、そうでない場合はfalse
。
使用可能なプラグインWooCommerceのバージョン
- WooCommerce 2.1.0 以降
使用可能なWordPressのバージョン
- WordPress 4.0 以降
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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_product_is_on_sale', 'mark_products_on_sale', 10, 2 );
function mark_products_on_sale( $on_sale, $product ) {
if ( has_term( '特別セール', 'product_cat', $product->get_id() ) ) {
return true;
}
return $on_sale;
}
引用元: –
サンプル2: カスタム条件によるセールの無効化
このフィルタは、特定の条件(ここでは在庫がない商品)でセールを無効化します。
add_filter( 'woocommerce_product_is_on_sale', 'disable_sale_for_out_of_stock', 10, 2 );
function disable_sale_for_out_of_stock( $on_sale, $product ) {
if ( ! $product->is_in_stock() ) {
return false;
}
return $on_sale;
}
引用元: –
サンプル3: 動的にセール価格を設定
このコードは、特定の価格以下の商品をセールとしてマークします。
add_filter( 'woocommerce_product_is_on_sale', 'dynamic_sale_mark', 10, 2 );
function dynamic_sale_mark( $on_sale, $product ) {
if ( $product->get_price() < 50 ) {
return true;
}
return $on_sale;
}
引用元: –
サンプル4: 商品のタグを基にセールを設定
商品に特定のタグが付いている場合にセール品としてマークします。
add_filter( 'woocommerce_product_is_on_sale', 'tag_based_sale', 10, 2 );
function tag_based_sale( $on_sale, $product ) {
if ( has_term( 'セール', 'product_tag', $product->get_id() ) ) {
return true;
}
return $on_sale;
}
引用元: –
サンプル5: セール中商品を特定の条件で強調表示
このフィルタは在庫が少ないセール商品を強調表示します。
add_filter( 'woocommerce_product_is_on_sale', 'highlight_low_stock_sales', 10, 2 );
function highlight_low_stock_sales( $on_sale, $product ) {
if ( $product->is_on_sale() && $product->get_stock_quantity() < 5 ) {
// セール表示として追加のロジックをここに入れる
return true;
}
return $on_sale;
}
引用元: –