Remove, not hide, options from variables dropdown menu in wooCommerece’s product pages

Remove, not hide, options from variables dropdown menu in wooCommerece’s product pages

Yesterday I had to find a way to show or remove specific options from the product variables dropdown menu.
My first thought was hiding using javascript or CSS, but in the end, some browsers (like the iPhone’s safari) keep show those.
If you looking at how to hide there are some interesting articles like this one
Anyway, the idea is re-write the dropdown adding a logic to decide when to show an option.

The following code shows a variable when a previously variable custom checkbox is set to yes.

function custom_woocommerce_dropdown_variation_attribute_options_html( $html, $args )
{
    $product = $args[ 'product' ];
    $attribute = $args[ 'attribute' ];
    $prodotto = wc_get_product( get_the_ID()  );		
    $product_price = $prodotto->get_price();

				
						
						$available_variations = $prodotto->get_available_variations();
						$terms = wc_get_product_terms( $product->get_id(), $attribute, array( 'fields' => 'all' ) );
							
						
						 $show_option_none_text = $args['show_option_none'] ? $args['show_option_none'] : __( 'Choose an option', 'woocommerce' ); // We'll do our best to hide the placeholder, but we'll need to show something when resetting options. 
						 $html = '<select id="' . esc_attr( $id ) . '" class="' . esc_attr( $class ) . '" name="' . esc_attr( $name ) . '" data-attribute_name="attribute_' . esc_attr( sanitize_title( $attribute ) ) . '" data-show_option_none="' . ( $show_option_none ? 'yes' : 'no' ) . '">'; 
						 $html .= '<option value="">' . esc_html( $show_option_none_text ) . '</option>'; 

						foreach ($available_variations as $key => $value) 
						{ 
			
	
							IF ((get_post_meta( $available_variations[$key]['variation_id'], 'licence_ppl', true )) == 'yes'){
								$html .= '<option value="' . esc_attr( $available_variations[$key]['attributes']['attribute_' . esc_attr( sanitize_title( $attribute ) ) . ''] ) . '" class="attached enabled">' . esc_attr( $available_variations[$key]['attributes']['attribute_' . esc_attr( sanitize_title( $attribute ) ) . ''] ) . '</option>'; 
							}else{
								//DO NOT PRINT
							}

						}
						 $html .= '</select>'; 
						
					
	
    return $html;
}
add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'custom_woocommerce_dropdown_variation_attribute_options_html', 10, 2 );

I used several interesting posts to write the code above, especially the ones to add price and stock number in the product variables dropdown, here.

Questions? Suggestions? Please leave a comment below.
I've really saved your ass? Buy me a beer

Leave a Reply

Your email address will not be published. Required fields are marked *

*