为WooCommerce缺货商品Variation标签添加自定义CSS类
Got it sorted! To add the out-stock class only to <label> elements corresponding to out-of-stock product variations, you can modify your custom product-variation.php template directly (since you already have access to it). Here's a step-by-step implementation:
Step 1: Update the product-variation.php Template
Locate the section in your template where the variation <label> is rendered. You’ll need to check each variation’s stock status and conditionally append the out-stock class to the label’s class attribute.
Here’s the adjusted code snippet:
// Ensure you have access to the variation object (adjust variable names if yours differ) $variation = wc_get_product( $variation_id ); // Create a conditional class string for out-of-stock variations $out_stock_class = !$variation->is_in_stock() ? 'out-stock' : ''; // Render the label with the dynamic class ?> <label class="<?php echo esc_attr( $out_stock_class ); ?> radio-label sw-radio-variation sw-radio-variation-<?php echo $variation_id; ?>" title="<?php echo esc_attr( $variation->get_name() ); ?>" for="<?php echo esc_attr( $attribute_name . '_' . $variation_id ); ?>"> <!-- Your existing label content (e.g., variation name, price) --> </label> <?php
Key Notes:
- Stock Check:
$variation->is_in_stock()returnstruefor available variations—we invert this to add the class only when stock is depleted. - Security: Always use
esc_attr()to sanitize class names and attributes to prevent XSS vulnerabilities. - Child Theme Best Practice: Copy the
product-variation.phpfile to your child theme’swoocommerce/single-product/folder before modifying it. This protects your changes from being overwritten during theme/WooCommerce updates.
Step 2: Style Out-of-Stock Labels (Optional)
Once the class is added, you can style the labels to make them visually distinct:
/* Example styles for out-of-stock variation labels */ .out-stock.radio-label { color: #888; opacity: 0.7; cursor: not-allowed; text-decoration: line-through; }
Alternative: Filter Hook (No Template Editing)
If you prefer not to modify the template, add this code to your child theme’s functions.php file to dynamically inject the class:
add_filter( 'woocommerce_variation_attribute_html', 'add_out_stock_class_to_variation_labels', 10, 4 ); function add_out_stock_class_to_variation_labels( $html, $attribute, $value, $variation ) { if ( !$variation->is_in_stock() ) { // Insert the out-stock class into the label's class attribute $html = str_replace( 'class="radio-label', 'class="out-stock radio-label', $html ); } return $html; }
内容的提问来源于stack exchange,提问作者user8597317

