Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Web-Assembler/7d73f81db1b4d3df07e96046481b2109 to your computer and use it in GitHub Desktop.
Save Web-Assembler/7d73f81db1b4d3df07e96046481b2109 to your computer and use it in GitHub Desktop.
Woocommerce sort Products > Attributes Table Labels
<?php
/**
* The following snippets allow you to custom-sort the Product Attributes Labels (i.e Attribute Taxonomy) in the table inside Products > Attributes.
* WooCommerce allows you to sort the terms of the Attribute but not the order of the Attributes themselves.
* Details on this thread: https://wordpress.org/support/topic/sorting-of-product-attributes/
* I have made my own "hack" solution that allows you to do this. You simply add a number followed by an underscore next to the Attribute Label. e.g. 100_My Attribute Name. If you wish to place another value above this you can use any number below 100 e.g. 67_My Other Attribute Name
*
* The array of values is sorted on this number and removed from displaying on the front end and when editing a product.
* Please be aware this is work in progress code and shouldn't be used on a live site without lots of testing.
*/
/**
* Custom function to iterate over each attribute label and remove the custom sorting number, e.g. '10_'
*
* @param array $attributes
* @return array $attributes Modified array
*/
function webassembler_restore_attribute_taxonomy_labels($attributes) {
foreach ($attributes as $key => $attribute) {
$attributes[$key]->attribute_label = preg_replace('/(\d+)_/i', '', $attribute->attribute_label);
}
return $attributes;
}
// Sort attributes in Products > Attributes admin page
function sort_attribute_taxonomy_labels($attributes) {
// Sort existing attributes by attribute label (Name field)
usort($attributes, function ($a, $b) {
return strnatcasecmp($a->attribute_label, $b->attribute_label);
});
// Only Remove the number from the label e.g. `10_` on the end if not in admin
if (!is_admin()) {
webassembler_restore_attribute_taxonomy_labels($attributes);
}
return $attributes;
}
add_filter( 'woocommerce_attribute_taxonomies', 'sort_attribute_taxonomy_labels' );
// Restore the original label when editing a Product's attributes
function restore_product_attribute_labels_edit_product() {
if (is_admin()) {
$screen = get_current_screen();
// Only show on products, but not when editing attributes
if ($screen->post_type !== 'product' || $screen->id === 'product_page_product_attributes') {
return;
}
// Get all product attributes
$all_attributes = wc_get_attribute_taxonomies();
webassembler_restore_attribute_taxonomy_labels($all_attributes);
}
}
add_action( 'current_screen', 'restore_product_attribute_labels_edit_product' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment