且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Wordpress标题数字排序功能

更新时间:2023-12-06 16:06:34

传递给MySQL并进行解释。 wp_posts.post_title 是数据库中的文本字段。



例如,

加上0强制MySQL试图将结果解释为一个数字。 选择'9'+ 0; 

返回(数字)9,

 选择'12'+ 0; 

返回(数字)12.如果MySQL将文本的值排序, 9之前(按字母顺序)。将值转换为数字后,按需要进行排序(数字顺序为12之前的9)。

注意,MySQL会将字符串的开始处尽可能多地转换为可能为一个数字,所以
  select'2abc'+ 0; 

返回2,但是

 选择'abc2'+ 0; 

返回0。


Learned this function from a guy, Utkarsh Kukreti, here http://www.fldtrace.com/wordpress/custom-post-types-numeric-title-order

Brilliant solution, it works for one of my category which contains the same title format (e.g. Bla 1, Bla 2...), but it didn't work well with my other category with just the alphabets and/or mix numbers.

My question is what does (wp_posts.post_title+0) mean here?

function orderby_post_title_int( $orderby ) { 
    return '(wp_posts.post_title+0) ASC'; 
}

That clause (eventually) gets passed to and interpreted by MySQL. wp_posts.post_title is a text field in the database. Adding 0 forces MySQL to try to interpret the result as a number.

For example,

select '9' + 0;

returns (the number) 9, and

select '12' + 0;

returns (the number) 12. If MySQL was sorting the values as text, it'd put 12 before 9 (in alphabetical order). With the values converted to numbers, it sorts as you need (9 before 12, in numerical order).

Note that MySQL converts as much of the beginning of the string as possible to a number, so

select '2abc' + 0;

returns 2, but

select 'abc2' + 0;

return 0.