skip to Main Content

WooCommerce-tables comes with classes like these, out of the box: shop_table shop_table_responsive cart woocommerce-cart-form__contents. So no table-class, which means no nifty Bootstrap-tables.

Huh!

And since overriding the WooCommerce-templates should only be done when absolutely necessary, then let’s solve it with JavaScript!

My entire site it encapsulated by a Vue-div, like so:

<div id="app">
  ...
  <table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents">
    ...
    ...
  </table>
  ... 
</div>

So initially I wrote this code, to add the table-class to all tables:

let tableSelectors = [
  '.some-class table',
  '.woocommerce-product-attributes',
  '.woocommerce-cart-form > table'
];
for( let t = 0; t < tableSelectors.length; t++ ){
  let tables = document.querySelectorAll( tableSelectors[t] );
  if( tables ){
    for( let i = 0; i < tables.length; i++ ){
      tables[i].classList.add( 'table' );
    }
  }
}

… Putting that in the mounted(){ ... }-section.

That worked! So far so good.

But WooCommerce is using jQuery quite a lot. And on the cart page, if I change the quantity (and press ‘Update’), then the table-contents are updated using AJAX. If you’re curious how it works, then you can check it out here.

And when that runs, I assume that WooCommerce grabs the initial cart-template and reloads that whole table; without the newly added table-class. Bah humbug!

So how can I solve this?

  1. I can override the WooCommerce ./cart/cart.php-template and add the
    class to the template. Seems like quite the overkill for adding a class.

  2. I can scan the DOM for tables every second (or so) and apply the table class, if it’s not there. Not cool… Regardless if it’s done using jQuery or Vue.

Since the whole table is being replaced in the DOM, then it doesn’t work to monitor the current table (using watch(){…} in Vue) and apply the class if it changes, – since it never changes (it’s replaced).

I’m unable to find a Hook that I can use.

I also tried using ajaxComplete, but I can see in the network-tab that the XHR-request is firing, but this code here is never doing anything (in the console):

jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
    console.log( 'Test' );
});

Any other suggestions?

4

Answers


  1. You could use the Mutation Observer API to listen for changes to a wrapper element’s contents and re-apply the table classes.

    This example is lifted nearly verbatim from the sample code on MDN. Clicking the button replaces the contents of the div, which you can see from the console output fires the observer callback.

    // Select the node that will be observed for mutations
    const targetNode = document.getElementById('some-id');
    
    // Options for the observer (which mutations to observe)
    const config = {
      childList: true,
      subtree: true
    };
    
    // Callback function to execute when mutations are observed
    const callback = function(mutationsList, observer) {
      for (let mutation of mutationsList) {
        if (mutation.type === 'childList') {
          console.log('A child node has been added or removed.');
        }
      }
    };
    
    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);
    
    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);
    
    function doUpdate() {
      targetNode.innerText = Math.random();
    }
    
    document.querySelector('button').addEventListener('click', doUpdate);
    <div id="some-id">(container)</div>
    <button>change</button>
    Login or Signup to reply.
  2. The ajaxComplete() function of jQuery can do what you expected,
    I don’t know why it’s not working for you.

    I just open the link of cart page you gave above and paste add the below code in the developer console
    and it works as expected after each update of the cart, the “table” class successfully appended to the table as per given selectors.

    jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
        jQuery('.some-class table, .woocommerce-product-attributes, .woocommerce-cart-form > table').addClass("table");
    }); 
    

    It looks like you have not added the code in the proper place. Since ajaxComplete() function is dependent on jQuery you need to execute the above code after jQuery has been loaded successfully. To do that you can use wp_add_inline_script() function with wp_script_is()

    Add the following code in your function.php file, It will add the below script to page after jQuery finish loading.

    function my_custom_script() {
       if ( ! wp_script_is( 'jquery', 'done' ) ) {
         wp_enqueue_script( 'jquery' );
       }
       wp_add_inline_script( 'jquery-migrate', 'jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
            jQuery(".some-class table, .woocommerce-product-attributes, .woocommerce-cart-form > table").addClass("table");
        });' );
    }
    add_action( 'wp_enqueue_scripts', 'my_custom_script');
    
    Login or Signup to reply.
  3. You can try to change the jquery ajax function

    (function ($) {
        var _oldAjax = $.ajax;
        $.ajax = function (options) {
            return _oldAjax(options).done(function (data) {
                $('.some-class table, .woocommerce-product-attributes, .woocommerce-cart-form > table').addClass("table");
                if (typeof (options.done) === "function")
                    options.done();
            });
        };
    })(jQuery);
    

    above code must be added before any ajax that is called

    Login or Signup to reply.
  4. i’ve tested it on your site using the javascript console and actually

    jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
      console.log( 'Test' );
    });
    

    fire pretty well.
    maybe you are adding that code on wrong place.. or maybe you have “Group Similar” flagged on javascript console settings and you didn’t notice the log

    so you could just put your code together like this:

    jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
      try{
        let tableSelectors = [
          '.some-class table',
          '.woocommerce-product-attributes',
          '.woocommerce-cart-form > table'
        ];
        for( let t = 0; t < tableSelectors.length; t++ ){
          let tables = document.querySelectorAll( tableSelectors[t] );
          if( tables ){
            for( let i = 0; i < tables.length; i++ ){
              tables[i].classList.add( 'table' );
            }
          }
        }
        console.dir("ok");
      }catch(ex){console.dir(ex);}
    });
    

    or use a jquery like solution like this:

    jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
        jQuery('.some-class table, .woocommerce-product-attributes, .woocommerce-cart-form > table').addClass("table");
    });
    

    i’ve tested both of them directly on your site and both solutions works pretty well

    and of course if you want make it works even at start the same script must be applied to jQuery( document ).ready() too:

    jQuery( document ).ready(function() {
        jQuery('.some-class table, .woocommerce-product-attributes, .woocommerce-cart-form > table').addClass("table");
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search