Hello,
Default woocommerce sorts titles a-z however it doesnt factor in numbers,
For example we have multiple products where numbers idenify the the size.following is the order they show on page:
Series Coupling – 10mm Hosetail
Series Coupling – 12mm Hosetail
Series Coupling – 06mm Hosetail
Series Coupling – 08mm Hosetail
Whereas this should go smallest to highest
06, 08,10,12
We also have values like 1/2 1/4 3/8
Ive tried to achieve this in a few ways but all are not working this is last test i did…
function custom_abc_number_sort($products) {
usort($products, function ($a, $b) {
$titleA = $a->get_title();
$titleB = $b->get_title();
// Extract numbers from the titles
preg_match(‘/\d+/’, $titleA, $numbersA);
preg_match(‘/\d+/’, $titleB, $numbersB);
// Convert extracted numbers to integers
$numberA = isset($numbersA[0]) ? (int)$numbersA[0] : PHP_INT_MAX;
$numberB = isset($numbersB[0]) ? (int)$numbersB[0] : PHP_INT_MAX;
// Remove numbers from titles for comparison
$titleA = preg_replace(‘/\d+/’, ”, $titleA);
$titleB = preg_replace(‘/\d+/’, ”, $titleB);
// Compare titles without numbers
$titleComparison = strnatcasecmp($titleA, $titleB);
if ($titleComparison === 0) {
return $numberA – $numberB; // Compare numbers if titles are the same
}
return $titleComparison;
});
return $products;
}
add_filter(‘woocommerce_get_catalog_ordering_args’, ‘custom_abc_number_sort’, 9999);
