Home / eCommerce / Force downloadable checkbox to be checked on the vendor product editor
Duplicate Snippet

Embed Snippet on Your Site

Force downloadable checkbox to be checked on the vendor product editor

Code Preview
php
<?php
/**
 * Force downloadable checkbox to be checked using MutationObserver
 */
function force_downloadable_checkbox_checked() {
    ?>
    <script type="text/javascript">
    (function() {
        // Function to check the downloadable checkbox
        function checkDownloadable() {
            var downloadableCheckbox = document.getElementById('_downloadable');
            if (downloadableCheckbox && !downloadableCheckbox.checked) {
                downloadableCheckbox.checked = true;
                console.log('Downloadable checkbox has been checked');
                
                // Create and dispatch a change event
                var event = new Event('change', { bubbles: true });
                downloadableCheckbox.dispatchEvent(event);
            }
        }
        
        // Set up a MutationObserver to watch for DOM changes
        var observer = new MutationObserver(function(mutations) {
            checkDownloadable();
        });
        
        // Start observing the document with the configured parameters
        observer.observe(document.body, { 
            childList: true,
            subtree: true
        });
        
        // Also check on initial load
        document.addEventListener('DOMContentLoaded', function() {
            checkDownloadable();
            
            // And check again after a delay to catch late-loading elements
            setTimeout(checkDownloadable, 1000);
            setTimeout(checkDownloadable, 2000);
            setTimeout(checkDownloadable, 3000);
        });
        
        // Also check when the window loads fully
        window.addEventListener('load', function() {
            checkDownloadable();
            setTimeout(checkDownloadable, 500);
        });
        
        // If jQuery is available, also set up some jQuery-specific handlers
        if (typeof jQuery !== 'undefined') {
            jQuery(document).ready(function($) {
                checkDownloadable();
                
                // When product type changes
                $(document).on('change', '#product-type', function() {
                    setTimeout(checkDownloadable, 100);
                });
                
                // After Ajax calls
                $(document).ajaxComplete(function() {
                    setTimeout(checkDownloadable, 100);
                });
            });
        }
    })();
    </script>
    <?php
}
// Add to both wp_footer and admin_footer to cover all bases
add_action('wp_footer', 'force_downloadable_checkbox_checked', 99);
add_action('admin_footer', 'force_downloadable_checkbox_checked', 99);

Comments

Add a Comment