概要
woocommerce_is_sold_individually
フィルタは、特定の商品が個別に販売されるべきかどうかを判定するために用いられます。このフィルタを使うことで、商品の設定に応じて、カートに追加できる数量を制限することが可能になります。具体的には以下のような機能を実装する際によく使用されます:
- 限定商品や特別なアイテムの数量制限
- 販促やキャンペーンに応じた購入数の調整
- 在庫管理の機能と連携した個別販売の設定
- ショッピングカートにおける購入制限の強化
- 特定の顧客グループに対する販売戦略
- 商品属性に基づいた販売条件のカスタマイズ
構文
apply_filters( 'woocommerce_is_sold_individually', $sold_individually, $product_id );
パラメータ
$sold_individually
(bool): デフォルトではfalse
。商品が個別に販売される場合はtrue
。$product_id
(int): 対象商品へのID。
戻り値
- このフィルタは、真偽値(trueまたはfalse)を返します。
使用可能なプラグインWooCommerceのバージョン
- WooCommerce 2.0 以上に対応。
ワードプレスのバージョン
- 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: 特定の製品のみ個別販売を許可する
このコードは、特定の製品IDに基づいて、その製品が個別に販売されることを強制します。
add_filter( 'woocommerce_is_sold_individually', 'custom_sold_individually', 10, 2 );
function custom_sold_individually( $sold_individually, $product_id ) {
// 製品ID 123 だけを個別販売
if ( $product_id === 123 ) {
return true;
}
return $sold_individually;
}
引用元: https://www.wpbeginner.com/
サンプルコード 2: カスタム製品属性に基づく販売制限
このコードでは、製品のカスタム属性に基づいて、個別販売の設定を行います。
add_filter( 'woocommerce_is_sold_individually', 'custom_attribute_sold_individually', 10, 2 );
function custom_attribute_sold_individually( $sold_individually, $product_id ) {
$product = wc_get_product( $product_id );
if ( $product->get_attribute( 'custom_attribute_name' ) === 'specific_value' ) {
return true;
}
return $sold_individually;
}
引用元: https://www.wpexplorer.com/
サンプルコード 3: 商品カテゴリに基づく個別販売設定
このコードは、特定のカテゴリに属する商品が個別に販売されるように設定します。
add_filter( 'woocommerce_is_sold_individually', 'category_based_sold_individually', 10, 2 );
function category_based_sold_individually( $sold_individually, $product_id ) {
$terms = get_the_terms( $product_id, 'product_cat' );
if ( $terms && ! is_wp_error( $terms ) ) {
foreach ( $terms as $term ) {
if ( $term->slug === 'exclusive' ) {
return true;
}
}
}
return $sold_individually;
}
引用元: https://www.sitepoint.com/
サンプルコード 4: ユーザーのロールに応じた販売設定
このサンプルコードでは、特定のユーザーロールのユーザーに対して、個別で商品の販売を許可します。
add_filter( 'woocommerce_is_sold_individually', 'role_based_sold_individually', 10, 2 );
function role_based_sold_individually( $sold_individually, $product_id ) {
if ( current_user_can( 'wholesale_customer' ) ) {
return false; // 卸売顧客には制限なし
}
return $sold_individually;
}
引用元: https://www.premiumwp.com/
サンプルコード 5: フィルタリング条件による個別商品の販売制限
このサンプルは、特定の条件を満たす場合に商品の個別販売を制限します。
add_filter( 'woocommerce_is_sold_individually', 'conditional_sold_individually', 10, 2 );
function conditional_sold_individually( $sold_individually, $product_id ) {
if ( is_product() && is_user_logged_in() ) {
return true; // ログイン中のユーザーに対しては個別販売有効
}
return $sold_individually;
}
引用元: https://www.themeum.com/