设置默认“管理库存?”创建新变体时选择“是”(Woocommerce)

问题描述 投票:0回答:1

我希望在创建新变体后,在 woocommerce 中默认选中“管理库存”(将一个子项添加到 .woocommerce_variations.wc-metaboxes.ui-sortable),但我的代码不值得

add_action( 'admin_footer', 'custom_admin_product_variations_js' );

function custom_admin_product_variations_js() {
    global $post_type;

    if ( 'product' === $post_type ) :
    ?><script type='text/javascript'>
    jQuery(function ($) {
        // Function to handle changes in the DOM
        function handleDOMChanges(mutationsList, observer) {
            $('#variable_product_options').on('change', function () {
                $('input.variable_manage_stock').each(function () {
                    if (!$(this).is(':checked')) {
                        $(this).attr('checked', 'checked').closest('div').find('.wc_input_stock').val(1);
                    }
                });
            });
        }

        // Create a MutationObserver
        const targetNode = document.querySelector('.woocommerce_variations.wc-metaboxes.ui-sortable');
        const config = { childList: true, subtree: true };

        const observer = new MutationObserver(handleDOMChanges);

        // Start observing changes in the DOM
        observer.observe(targetNode, config);
    });
    </script><?php
    endif;
}


我已经尝试了 stackoverflow 中有关此特定问题的所有帖子。

wordpress woocommerce hook
1个回答
0
投票

这是我已经测试过并且有效的脚本

jQuery(document).ready(function ($) {
    function observeVariationChanges() {
        var variationContainer = $('.woocommerce_variations.wc-metaboxes.ui-sortable');

        if (variationContainer.length) {
            $('.variable_manage_stock').attr('checked', 'checked');
            $('.show_if_variation_manage_stock').show();
        }
    }

    // Use a MutationObserver to detect DOM changes
    var observer = new MutationObserver(observeVariationChanges);

    // Start observing changes
    observer.observe(document.body, { childList: true, subtree: true });
});
© www.soinside.com 2019 - 2024. All rights reserved.