John Davidson

php - Remove particular variation from dropdown in WooCommerce frontend

0 comments
Message:


I am using WooCommerce and WooCommerce Subscriptions and its working as per my expectations.


Now I am creating a variable subscription product having multiple attributes like this.





Now I want to remove/hide particular item from dropdown hence I am trying to use below code / hook which I believe might help me to achieve.


add_filter('woocommerce_dropdown_variation_attribute_options_args', 'hide_variations_for_mindesk_users');

function hide_variations_for_mindesk_users( $args ){

print_r($args);

return $args;
}

Now my question is, how can I remove or hide particular variation product from dropdown? Do I need to remove from variation id or from somewhere?




For example:


Here I want to remove/hide 2nd variation from dropdown which has variation id #4171 having "Monthly- Professional". This should work with single attribute as well.


Can anyone point me in the right direction to achieve this?



My Answer:
To remove or hide a particular variation from the dropdown in WooCommerce, you can modify the $args array in the 'woocommerce_dropdown_variation_attribute_options_args' filter hook. You can achieve this by checking the variation ID and excluding it from the options array.

Here is an example code snippet that demonstrates how to remove a specific variation from the dropdown:

php
add_filter('woocommerce_dropdown_variation_attribute_options_args', 'hide_variations_for_mindesk_users');

function hide_variations_for_mindesk_users( $args ){
// Check if we are on the product page
if( is_product() ){
// Define the variation ID to be hidden
$variation_id_to_hide = 2;

// Get the product variations
$product = wc_get_product();
$variations = $product->get_available_variations();

// Loop through the variations and remove the one to be hidden
foreach( $variations as $key => $variation ){
if( $variation['variation_id'] == $variation_id_to_hide ){
unset( $args['options'][ $key ] );
}
}
}

return $args;
}


In this code snippet, we first check if we are on the product page. Then, we define the variation ID that we want to hide. We retrieve the product variations and loop through them to find the variation with the specified ID. If we find it, we remove it from the options array in the $args variable.

You can modify the $variation_id_to_hide variable to match the ID of the variation you want to hide. This code should help you achieve the desired functionality of removing a specific variation from the dropdown in WooCommerce.

Rate this post

5 of 5 based on 8627 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us