wp query - Case insensitive ORDERBY in wpquery

admin2025-01-07  5

I'm trying to sort custom posts in alphabetical order, and I've just now realized that capital letters are being sorted before lowercase. Two restaurants start with 'Cal' and 'CAT' with 'CAT' being returned as the first in alphabetical order.

Here're my $args:

$args = array(
    'numberposts' => -1,
    'post_type' => 'chef',
    'meta_key' => 'restaurant',
    'orderby' => 'meta_value',
    'order' => 'ASC'
);

I've also tried changing the 'orderby' to 'LOWER(restaurant)' but had no success with that.

I'm trying to sort custom posts in alphabetical order, and I've just now realized that capital letters are being sorted before lowercase. Two restaurants start with 'Cal' and 'CAT' with 'CAT' being returned as the first in alphabetical order.

Here're my $args:

$args = array(
    'numberposts' => -1,
    'post_type' => 'chef',
    'meta_key' => 'restaurant',
    'orderby' => 'meta_value',
    'order' => 'ASC'
);

I've also tried changing the 'orderby' to 'LOWER(restaurant)' but had no success with that.

Share Improve this question edited Nov 19, 2018 at 22:52 KingRichard asked Nov 19, 2018 at 21:43 KingRichardKingRichard 1771 silver badge11 bronze badges 1
  • Please edit your question to provide more context (is your $args argument used in a WP_Query, or pre_get_posts, or (shudder) query_posts(), for example). – Pat J Commented Nov 20, 2018 at 17:38
Add a comment  | 

2 Answers 2

Reset to default 0
  1. As stated above, your orderby parameter should be set to meta_value, not restaurant.

  2. Using phpMyAdmin or some other tool, look at your database. With any newer installation of WordPress, your tables should have a collation of utf8mb4_unicode_ci. That means that the table is storing its data in UTF-8 4-byte unicode character set. That "ci" at the end means "case insensitive".

If your collation is not correct, then you may need to convert your data. This is not as easy as it sounds all the time, so make sure you get a quality backup of your database first.

It looks like you may have set your orderby incorrectly... you don't set the metakey and orderby to the same.

try changing

'orderby' => 'restaurant',

to

'orderby' => 'meta_value',

this link may help https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736264384a964.html

最新回复(0)