skip to Main Content

I have this jQuery, which makes changes to product variations of a WooCommerce product page. It works in the FireFox console just fine, but it has no effect on the page when I add it. In order to make it load last, I placed the code in the footer. There is nothing loading after this. It may be that WooCommerce’s own jQuery nevertheless loads the elements I’m targeting after the page load (?). I don’t know, but I’ve been fighting with it long enough that it’s time to reach out for help.

jQuery('.variations select option').each(function() {
    if ( jQuery(this).is(':disabled') ) {
        jQuery(this).css('display','none');
    }
});

Thanks

2

Answers


  1. You need to select the elements once the DOM has fully loaded, for jQuery, you just place your code inside the event handler for document ready as shown below. Placing lower in the HTML structure isn’t enough with WordPress in most cases.

    jQuery(document).ready(function(){
        jQuery('.variations select option').each(function() {
            if ( jQuery(this).is(':disabled') ) {
                jQuery(this).css('display','none');
            }
        });
    });
    
    Login or Signup to reply.
  2. To target product variation single pages only, you can use the following hooked function, with your jQuery revisited code (waiting for DOM to be totally loaded):

    add_action( 'woocommerce_after_variations_form', 'jquery_script_after_variations_form' );
    function jquery_script_after_variations_form() {
        ?>
        <script type="text/javascript">
        (function($){
            $('.variations select option').each( function() {
                if ( $(this).is(':disabled') ) {
                    $(this).css('display','none');
                }
            });
        })(jQuery);
        </script>
        <?php
    }
    

    Code goes in functions.php file of the active child theme (or active theme). It should work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search