Natural sort Wordpress post titles (alphabetically

2019-08-05 05:30发布

Is there any possible way to sort a new Wordpress post query by the title, but numerically instead of alphabetically?

I have some titles that have a lot of the same name alphabetically, then have a number afterwards, so of course for example Wordpress is putting title12 ahead of title1.

$args = array( 
'orderby'=> 'title', 
'order' => 'ASC',
);
$loop = new WP_Query( $args );

I know we have this functionality to sort titles in ascending order, but it does not sort titles like that:

Title 1
Title 2 

Please let me know if we any work around using WP query ? Thanks for your help in advance :)

1条回答
做自己的国王
2楼-- · 2019-08-05 06:18

Try adding this immediately after your code above:

usort($loop->posts, function($a,$b) {
   return strnatcmp($a->title, $b->post_title);
});
查看更多
登录 后发表回答