Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let users sort posts in Wordpress

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.

like image 950
andy Avatar asked Dec 10 '13 15:12

andy


People also ask

How do I sort posts in WordPress?

After activating it click into “Post Types Order” under settings and you can enable the types of posts you want the reorder interface to show up on. Then under that post type you will see a new menu called “Re-order.” You can then drag and drop the posts within according to the order you want them to appear in.

How do I show post in ascending order in WordPress?

Good answer, and orderby is used to tell WP what is your order-key... example : orderby='date', or orderby='title', orderby='author' etc.


1 Answers

Try Simple Custom Post Order plugin.

It is using AJAX and JavaScript, you don’t have to load anything else. You have to just drag and drop the posts.

like image 186
Krunal Shah Avatar answered Sep 30 '22 22:09

Krunal Shah