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'; 
}
Randize
  • 121
  • 1
  • 10

1 Answers1

0

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.

Hobo
  • 7,536
  • 5
  • 40
  • 50
  • I get, so when there's no number in the post_title, it will return as 0 as well. Which means with this function, nothing can be ordered. Thanks man! I think I know how to fix this. I'll let the post_title sort in alphabetical order if the value is 0, and in numerical order when the value is equal or greater than 1. Basically using + 1. Correct me if I'm wrong. By the way, if the string is 'abc 2', spacing the number and letters, the return value would be 2 right? – Randize Mar 15 '12 at 13:29
  • Sorry, I can't get to a MySQL session to check, but I'm pretty sure 'abc 2' + 0 would return 0 (that it tries to evaluate from the start of the string). If you're not having any luck, and can explain the order you're after with some example titles (probably best as a separate question) I'm sure someone will be able to help. – Hobo Mar 16 '12 at 18:14