0

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?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Elron
  • 1,235
  • 1
  • 13
  • 26

1 Answers1

0

Not gunna touch the code, but Strawberry's suggestion of ordering the field modifies the sql like this:

select * 
from your_table 
order by field(custom_order, "1","3","4","6","8","68","103","8L","11","19","67","86","107","9L")
;

I've assumed that custom_order is stored as a varchar or other string type hence the quotes around the integers.

Lnr
  • 187
  • 1
  • 7
  • Thanks, @Lnr. The thing is the field items are dynamically changed per post - I can't predict the values of the custom field. – Elron May 10 '20 at 08:02