Skip to content

Instantly share code, notes, and snippets.

@hereswhatidid
Created May 4, 2016 15:53
Show Gist options
  • Select an option

  • Save hereswhatidid/88ffd83eb2e2840c43e589f30f335b4f to your computer and use it in GitHub Desktop.

Select an option

Save hereswhatidid/88ffd83eb2e2840c43e589f30f335b4f to your computer and use it in GitHub Desktop.
Show variation SKUs on the Product admin screen for WooCommerce
jQuery( document ).ready( function() {
jQuery( '#woocommerce-product-data' ).on( 'woocommerce_variations_loaded', function() {
var $panels = jQuery( this ).find( '.woocommerce_variation' );
$panels.each( function() {
var sku = jQuery( this ).find( '.sku input' ).val();
if ( sku ) {
jQuery( this ).find( 'h3 > strong' ).text( 'SKU: ' + sku );
}
} );
} );
} );
@hereswhatidid
Copy link
Copy Markdown
Author

This is helpful for maintaining product variations where the SKU is more admin-friendly than the internal WordPress post ID.

@shaunjc
Copy link
Copy Markdown

shaunjc commented May 9, 2018

It seems the selector is a little out of date and .sku input no longer works. Changing it to input[name*="variable_sku"] works just well.

Replacing the ID with the SKU sometimes made the attribute dropdown move out of line with one another, so I appended it instead. I also used the admin_print_scripts action to output the javascript directly to the page as opposed to loading the external js file. Example code shown below.

<?php
// Use the admin_print_scripts action to put the script directly onto the page.
add_action( 'admin_print_scripts', function() {
    // Allow multi-line strings and both sets of quotation marks without escaping by using NOWDOC notation.
    echo <<<'JSND'
<script type="text/javascript">
jQuery(function($){
    $('#woocommerce-product-data').on('woocommerce_variations_loaded', function() {
        $(this).find('.woocommerce_variation').each(function() {
            var self = $(this),
                  // Updated selector to account for WooCommerce updates.
                  sku = self.find('input[name*="variable_sku"]').val();
            if (sku) {
                // Append SKU to ensure attributes are still more or less in line.
                self.find('h3').append($('<strong/>').text('SKU: ' + sku));
            }
        });
    });
});
</script>
JSND;
// Make sure jQuery has loaded - PHP_INT_MAX may be a little excessive, but it works as expected.
}, PHP_INT_MAX );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment