wordpress 创建新变体时,将默认“管理库存?”设置为“是”(Woocommerce)

ylamdve6  于 12个月前  发布在  WordPress
关注(0)|答案(1)|浏览(129)

我想“管理库存”在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中关于这个特定问题的所有帖子。

qv7cva1a

qv7cva1a1#

这里是一个脚本,我已经测试和工程

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 });
});

字符串

相关问题