如何在WooCommerce中检查自定义产品类型选项是否勾选?
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

