Hide variable product dropdown that has a unique variation selected by default in Woocommerce

喜你入骨 提交于 2019-12-08 08:14:54

问题


I have a unique issue. I am using a plugin where they are not able to support the request. I need to split out variations into separate items, but if I copy and paste and turn them into a simple product, then I can't sync the count for the product to track inventory stock. As a workaround I needed to be able to disable the variations I do not need, keeping only the one that I do need. But here is where I am having trouble. If I have one variation enabled, then I do not want to show the dropdown, and instead want it to look like a simple product on the UI. I tried everything and cannot get it to work.

I even tried using

add_filter( 'woocommerce_hide_invisible_variations', '__return_true', 10, 3 );

with no success as they are visible and not hidden even though the counts are 0, the price is 0, and the item is disabled.

How can I show the product page with no drop-down? Take it one step further; I delete all variations except the one that I need to keep. I need to keep it in variations mode due to the plugin that syncs. How do I display it without any dropdowns showing?

Example logic:

If product type is a variation and enabled count == 1 then special ui display, else normal.

Thanks.


回答1:


IMPORTANT: The code only works when the unique variation is selected as default form value:

The following code will hide from variable products that have only one variation enabled and selected by default, the attribute dropdown and the selected variation price:

add_action( 'woocommerce_before_add_to_cart_form', 'single_unique_variation_ui', 10 );
function single_unique_variation_ui(){
    global $product;

    if( ! $product->is_type('variable') )
        return; // Only variable products

    $available_variations = $product->get_available_variations(); // Get available variations
    $default_attributes   = $product->get_default_attributes();   // Get default attributes

    // Only for a unique selected variation by default
    if( ! ( sizeof($available_variations) == 1 && sizeof($default_attributes) == 1 ) )
        return;

    // Get the unique variation
    $variation = reset($available_variations);

    // Loop through
    if( reset($variation['attributes']) == reset($default_attributes) ) :
    // Styles
    ?>
    <style>
        div.woocommerce-variation-price, table.variations { display:none; }
    </style>
    <?php
    endif;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Without the code (the normal woocommerce behavior):

With the code (that hide the attribute dropdown and the price):

It will give you the same UI than simple products



来源:https://stackoverflow.com/questions/52564972/hide-variable-product-dropdown-that-has-a-unique-variation-selected-by-default-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!