提问人:Davi Davi Amrico Amrico 提问时间:11/7/2023 最后编辑:Davi Davi Amrico Amrico 更新时间:11/7/2023 访问量:36
创建新变体时,将默认的“管理库存”设置为“是”(Woocommerce)
Set default "Manage Stock?" to "yes" when a new variation is created (Woocommerce)
问:
我希望在创建新变体后立即在 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 中关于此特定问题的所有帖子。
答:
0赞
Snuffy
11/7/2023
#1
这是我测试过并有效的脚本
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 });
});
评论