You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce中检查自定义产品类型选项是否勾选?

How to Check Custom 'Event' Product Type Option Like is_virtual() in WooCommerce

Hey there! Great job setting up that custom "event" product type option. To check if it's enabled using a clean, WooCommerce-native approach (just like the built-in is_virtual() method), here's the best implementation:

1. Add a Custom Method to the WC_Product Class

The most seamless way is to extend the WC_Product class with your own is_event() method. This lets you check the option exactly like you would with any default product property:

// Register the custom is_event() method for WooCommerce products
add_action('woocommerce_init', function() {
    // Avoid duplicate method errors
    if (!method_exists('WC_Product', 'is_event')) {
        // Create an alias for the original class to extend it
        class_alias('WC_Product', 'WC_Product_Original');
        
        class WC_Product extends WC_Product_Original {
            /**
             * Check if the product is marked as an event
             * @return bool
             */
            public function is_event() {
                return 'yes' === $this->get_meta('_event');
            }
        }
    }
});

2. Use the Method Anywhere You Have a Product Object

Once the method is added, you can call it just like is_virtual():

Example in a Product Loop

if ( $product->is_event() ) {
    echo '<div class="event-badge">This is an Event Product!</div>';
}

Example in a Single Product Template

global $product;
if ( $product->is_event() ) {
    // Add event-specific content
    echo '<h3>Event Details</h3>';
}

3. Helper Function for Post ID-Based Checks

If you only have a product ID (not a full WC_Product object), use this helper function:

/**
 * Check if a product (by ID) is marked as an event
 * @param int $product_id
 * @return bool
 */
function is_product_event( $product_id ) {
    return 'yes' === get_post_meta( $product_id, '_event', true );
}

// Usage example
if ( is_product_event( get_the_ID() ) ) {
    // Execute event-specific logic
}

Why This Works

Your existing code correctly saves the _event meta field as either "yes" or "no" when the product is saved. The methods above simply read this meta value and return a boolean, matching the behavior of WooCommerce's built-in product property checks.


内容的提问来源于stack exchange,提问作者D_P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:06:22