Skip to content

Instantly share code, notes, and snippets.

@vovadocent
Created June 28, 2023 10:40
Show Gist options
  • Save vovadocent/1e15656d39737145275ab6f2ab2b74c3 to your computer and use it in GitHub Desktop.
Save vovadocent/1e15656d39737145275ab6f2ab2b74c3 to your computer and use it in GitHub Desktop.
WP Query order by alphanumeric meta value
<?php
function orderbyReplace($orderby)
{
global $wpdb;
// use this if you have stable literal prefixes (e.g. af102, af56, af2569)
$new = str_replace($wpdb->prefix . 'postmeta.meta_value ASC', 'LENGTH(mt1.meta_value) ASC, mt1.meta_value ASC', $orderby);
// use this if you have something like (102bch, 56dbg, 2569, 12ea)
$new = str_replace($wpdb->prefix . 'postmeta.meta_value ASC', 'CAST(mt1.meta_value as UNSIGNED) ASC, mt1.meta_value ASC', $orderby);
return $new;
}
$args = [
'post_type' => 'mycpt',
'order' => 'ASC',
'posts_per_page' => -1,
'meta_key' => 'my-meta-key',
'orderby' => 'meta_value',
'meta_query' => [
[
'key' => 'my-meta-key',
'value' => '',
'compare' => 'LIKE'
],
]
];
add_filter('posts_orderby', 'orderbyReplace');
$q = new WP_Query($args);
remove_filter('posts_orderby', 'orderbyReplace');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment