Order WordPress Posts by Title Using jQuery

Published on : December 29, 2016

Author:

Category: Wordpress


If you failed to order your post by post title using WordPress query chances are the following jQuery snippet will come in handy.

Suppose you have a div and element like this generated after WordPress query.

<div class="order-title">

<a href="#">lorem ipsum</a>

<a href="#">dolor set</a>

<a href="#">amet lorem/a>

</div>

Now if you want to manage the links from the WordPress loop and sort them alphabetically by jQuery then give it a try.

<div class="order-title">

//loop code starts (you know how to run a WordPress loop.)

<a data-order="'.substr( get_the_title($post->ID), 0, 1 ).'" href="<?php get_the_permalink($post->ID);?>"><?php get_the_title($post->ID);?></a>

//loop code ends

</div>

I have added a data attribute named “data-order” to the link and added the post title’s first alphabet to the link, the output like this.

<div class="order-title">

<a data-order="l" href="www.sample1.com/3/">lorem ipsum</a>
<a data-order="d" href="www.sample1.com/2/">dolor set</a>
<a data-order="a" href="www.sample1.com/1/">amet lorem/a>
</div>

Now we will add our jQuery code to the div’s children to make them alphabetically ordered.

<script>
 var mylist = jQuery('div.order-title');
 var listitems = mylist.children('a').get();
 listitems.sort(function(a, b) {
 var compA = jQuery(a).attr('data-order').toUpperCase();
 var compB = jQuery(b).attr('data-order').toUpperCase();
 return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
 })
 jQuery.each(listitems, function(idx, itm) { mylist.append(itm); });
 </script>

Now the question is what the code will do? the code will get the children of the div’s and get the “data-order” attribute value of the link and then compare the value with others until they are sorted alphabetically. Sounds fun, isn’t it?

The output will be something like this.

<div>

<a data-order="a" href="www.sample1.com/1/">amet lorem</a>
<a data-order="d" href="www.sample1.com/2/">dolor set</a>
<a data-order="l" href="www.sample1.com/3/">lorem ipsum/a>
</div>

Hope you will find it helpful. Thanks and I look forward to receiving your thoughts.