Let users sort posts in Wordpress

Viewed 3863

I’d like to create a page for filtering posts based on a number of criteria.

I can work with wp_query and deliver posts quite easily, my problem is that I can’t figure out (nor can I find any answers online about this, believe me I looked) how to let users do this.

Take this for example, returns the posts in order of price (custom field meta value) from highest to lowest with 33 posts.

<?php 

$featuredPosts = new WP_Query( array(
'posts_per_page' => 33,
   'meta_key'=>'Price',
   'orderby' => 'meta_value_num',
   'order' => DESC
) );

?>

<?php if ( $featuredPosts->have_posts() ) : ?>

<?php while ( $featuredPosts->have_posts() ) : $featuredPosts->the_post(); ?>

<article <?php post_class('item-post block'); ?> id="post-<?php the_ID(); ?>">
<h2 class="price-title"><?php the_title(); ?> </h2>

</article> <!-- end div post -->

<?php endwhile; wp_reset_query(); ?>

<?php endif; ?>

Now, even after reading and googling, I’ll be damned if I can figure out how I’d implement this on the front end for users to filter posts.

I mean, I know you can append to the URLs in Wordpress to alter the order of posts, but in this context I’m totally lost.

I tried this, but it doesn't work.

<?php

$by_price = esc_url(add_query_arg(array(
    'meta_key' => 'price',
    'orderby' => 'meta_value_num',
    'order' => ASC
)));
$by_date = esc_url(add_query_arg(array(
    'orderby' => 'date',
    'order' => DESC
)));

?>

<ul>
    <li><a href="<?php echo $by_price;?>">Order by price</a></li>
    <li><a href="<?php echo $by_date;?>">Order by date</a></li>
</ul>

What I’m trying to achieve is actually quite simple as well, let the user choose the category, choose the price range (guessing I’d write something in JQuery to deliver a value into an field), set the number of results they’d like to be returned.

I’ve tried googling everything under the sun I can think of for this, no dice.

3 Answers
Related