I want to sort my posts by a custom field called "custom_order".
The "custom_order" field will have value that can have number / letters / both, for example:
[103,3,4,6,8,"8L",67,1,11,19,68,86,107,"9L"];
Example: post 1 custom_order
field is -> 103
;
Example: post 2 custom_order
field is -> 3
;
Example: post 3 custom_order
field is -> 4
;
... posts 4 5...
Example: post 6 custom_order
field is -> 8L
;
And so on...
I want WordPress to sort the posts by numbers & letters.
So this would be the good order:
[1,3,4,6,8,"8L","9L",11,19,67,68,86,103,107];
<-- Notice this combined alphabetical & numeral sort (6,8,8L,9L)
I'm using this function in functions.php
and it indeed sorts the posts, but in the wrong order:
[1,3,4,6,8,68,103,"8L",11,19,67,86,107,"9L"]
<-- Notice that 68 comes before 11, 9L comes after 107 and more problems.
add_action('pre_get_posts', function ($q) {
if (
!is_admin() // Target only front end queries
&& $q->is_main_query() // Target the main query only
&& ($q->is_search() || $q->is_post_type_archive('data-base'))
) {
$q->set('meta_key', 'custom_order');
$q->set('order', 'DESC');
$q->set('orderby', 'meta_value');
}
});
I found a solution that sorts the array in JavaScript in the correct way, but I can't manage to make it work in WordPress.
Any idea of an approach to solving this?