Thursday, May 30, 2013

Sorting posts by first letter in Wordpress

So after taking a look at pieces of code I printed out from this amazing tutorial: http://wp.tutsplus.com/tutorials/getting-loopy-ajax-powered-loops-with-jquery-and-wordpress/

I figured out how to display posts by the letter of the button they click on.  To start, in my index.php, I inserted this above the post loop I had before:
<?php $l = 'A';?>
<div id="sort-by">
<a name="0-9">0-9</a>
<?php
while (strlen($l) <= 1) {
?> <a name="<?php echo $l; ?>"><?php echo $l; ?></a><?php
++$l;
}
?>
</div> <!-- #sort-by -->

<div id="alphebatized">
</div> <!-- #alphebatized -->


The while loop loops though all the uppercase letters by simply adding 1 to $l and prevents it from going past Z by checking if its length is >= 1.  The alphebatized div is where all the posts for the letter selected will go.

I've added a couple functions to my functions.php that were posted by the moderator on here: http://wordpress.org/support/topic/what-argument-to-use-in-query_posts-to-get-posts-with-given-letter
These functions allow you to query letters using the query_posts function: http://codex.wordpress.org/Function_Reference/query_posts

Then I created a javascript file, named active.js, put it in the js directory and added the following code to it: http://pastebin.com/pu2dCRsJ
This makes heavy use of .ajax() which is put into a function and assigned to the load_posts var for use.      Before the GET request is sent, the content (list of posts) will fade out quickly.  After, when the request gets sent the content, and then the data, will fade in quickly.  Any existing content is also cleared and the content for the newly selected letter gets appended to it.  Since this function is loaded on page load, there won't be a value for l.  So when this is the case l automatically equals 'a'.  The request gets sent to my first-letter.php.

Lastly, for my first-letter.php I have the following code: http://pastebin.com/Py6SvX0b
This just grabs the letter from the request, puts it in a query_posts, and then prints out all the matching posts.  wp_reset_query() is added to reset query_posts for the other loop in index.php.


So as of now I see no problems with this so I'm going onto styling everything with css.  I hope to be done by very late tonight.

No comments:

Post a Comment