Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Jasper Holtjer
Jasper Holtjer
3,370 Points

How to let your users sort your (custom) post archive

So, I got a custom loop (see beneath) and it's working perfectly. But I'd like to add some filters to let users sort the posts in the overview (archive) by different parameters. Like title, number of pages or date published.

Now I've found some jQuery (like Isotope @ http://isotope.metafizzy.co/sorting.html) which should do the job. But is this the best way to do this? Or is there something build within WordPress what offers a better alternative?

Thanks in advance, Jasper

<?php
// WP_Query arguments
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array (
    'post_type'             => array( 'book' ),
    'posts_per_page'        => 12, 
    'paged'                 => $paged,
);

// The Query
$query = new WP_Query( $args );    

// Start the Loop.
while ( $query->have_posts() ) : $query->the_post();

    get_template_part( 'template-parts/post-book' );

// End the loop.
endwhile;

// If no content, include the "No posts found" template.
else :
get_template_part( 'template-parts/content', 'none' );

endif;
?>     

2 Answers

Casey Ydenberg
Casey Ydenberg
15,622 Points

The trouble with a JavaScript solution is that it will only sort things which are already loaded on the page. This might be OK, but you should change posts_per_page to -1 to make sure all your posts come up. If you do go this route, Isotope is a pretty great package and might help you out a lot.

On other cases, the number of posts might exceed what you want to deliver in a single request. In that case you can add Order and Orderby parameters to your WP_Query, expose the options you want to to your user via a form, and change the order upon page reload via GET.

Jasper Holtjer
Jasper Holtjer
3,370 Points

First of all, thanks for your remark! I didn't know the JavaScript won't order all items when they aren't on the page. I got a very long list, so "post_per_page to -1" is not an option.

I'll take a look into the GET solution, unfortunately I'm not experienced with that function. Do you know of any tutorials about it here at Treehouse?