Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

I am using a custom field with a simple integer value to order my posts, but they’re not sorting correctly. Why?

0
Posted

I am using a custom field with a simple integer value to order my posts, but they’re not sorting correctly. Why?

0

Short answer: you need to zero-pad the integers if you want them to sort numerically. (‘001′, ‘002′, ‘010′, etc.) This is a side effect of the WordPress data design. The ‘meta_value’ field in the wp_postmeta table is defined as type ‘longtext’. This means that any integer stored in the meta_value field is automatically converted into a string. Therefore any sort on the meta_value field is a string sort, not an integer sort. In a string sort, ‘10′ comes before ‘2′. That is why it is necessary to zero-pad the integers in order to sort them numerically. Note that you do not have this problem when sorting on menu_order, because the menu_order field is defined as type ‘int’. So if you want to use simple integers to sort your posts, it would be better to do it using a plugin like PostMash which stores the values in the menu_order field.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123