开发者

Wordpress custom post ordering problem

开发者 https://www.devze.com 2023-01-10 01:25 出处:网络
I am ordering my posts by using a custom field \"order\". For each post the value of order is a number, which dictates where I wa开发者_C百科nt the post to be positioned.

I am ordering my posts by using a custom field "order".

For each post the value of order is a number, which dictates where I wa开发者_C百科nt the post to be positioned.

I have the following:

query_posts('category_name=category&meta_key=order&orderby=meta_value&order=ASC');

This seems to have worked fine up until post #10, this posts positions itself at 2nd in the list.

Any ideas as to where I am going wrong?


WordPress is treating the values as string to sort, so 10 comes after 1, just change following

orderby=meta_value

to (values will be treated as number)

orderby=meta_value_num

When sorting by number, use meta_value_num instead of meta_value to make WordPress tret the value as a number instead of string.

I had the same problem, Sheikh Heera helped me out and it works like a charm.


Ok, found the answer elsewhere.

Because the custom field value is alphabetic and not numeric. You have to begin your ordering with 01, 02, 03...10, 11

and not 1, 2, 3...10, 11


Another option is to create a custom query string that casts your alphabetic custom field as a decimal in the ORDER BY clause:

$querystr = "
    SELECT wposts.*
    FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
    WHERE wposts.ID = wpostmeta.post_id
    AND wpostmeta.meta_key = 'your-custom-field-name' 
    AND wposts.post_type = 'post'
    ORDER BY CAST(wpostmeta.meta_value AS DECIMAL) DESC
";
0

精彩评论

暂无评论...
验证码 换一张
取 消