Reputation: 407
How can I hide a variation from the dropdown on a product page, but still let it be purchased through WooCommerce URL coupons?
If I make the variation not active, it is hidden from the drop down, but I get the message "This product can not be purchased" in cart. I just want to hide it from the list, not disable it entirely.
Upvotes: 6
Views: 16970
Reputation: 1
I'm pretty new here and to playing with code generally, but I used css in the Customizer to hide a variation called "Student:"
.postid-403 option[value=Student]{display: none;}
postid-403 identifies my product page. This seems to be working. Any reason not to do it this way?
Upvotes: 0
Reputation: 3899
The following solution worked on my theme, but you're running Bootstrap so you may have issues.
We'll modify the option
tag of the options you want hidden with the hidden
attribute. Take the following code and add it to your theme's functions.php
or a custom plugin:
Custom Code
function custom_woocommerce_dropdown_variation_attribute_options_html( $html, $args )
{
$product = $args[ 'product' ];
$attribute = $args[ 'attribute' ];
$terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );
$options = $args[ 'options' ];
if ( empty( $options ) && !empty( $product ) && !empty( $attribute ) ) {
$attributes = $product->get_variation_attributes();
$options = $attributes[ $attribute ];
}
foreach ( $terms as $term ) {
if ( in_array( $term->slug, $options ) && ***SOME CONDITION***) {
$html = str_replace( '<option value="' . esc_attr( $term->slug ) . '" ', '<option hidden value="' . esc_attr( $term->slug ) . '" ', $html );
}
}
return $html;
}
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'custom_woocommerce_dropdown_variation_attribute_options_html', 10, 2 );
Note that some browsers don't recognise the hidden
attribute. If you want full cross browser compatibility, you'll want to look at the answers at How to hide a <option> in a <select> menu with CSS?. Adding css property style="display:none"
may also work with some browsers.
Advanced Custom Fields
Now, in the code above, I've written ***SOME CONDITION***
. This condition needs to check whether an option should be hidden or not. To add this information we need to create a custom field for the attribute. You can do this manually, but I do it with the Advanced Custom Fields Plugin (ACF).
Taxonomy Term
is equal to
Product **your attribute**
.***SOME CONDITION***
and replace it with get_field( 'hidden', $term ) )
. This is an ACF function which will get the value of the 'hidden' field for that attribute's tern.After all that, the terms you ticked as hidden should not appear in the dropdown on the product page. In my example you can see green is missing from the dropdown.
Upvotes: 4