Saurabh
Saurabh

Reputation: 33

Natural sort Wordpress post titles (alphabetically and numerically)?

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 :)

Upvotes: 2

Views: 2018

Answers (1)

cpilko
cpilko

Reputation: 11852

Try adding this immediately after your code above:

usort($loop->posts, function($a,$b) {
   return strnatcmp($a->title, $b->post_title);
});

Upvotes: 3

Related Questions