Question

I'm trying to set up a dropdown that would sort my posts by Newest to oldest and Alphabetical. This is what I have so far:

I'm declaring an empty variable, then a form where I can change the contents of this empty variable.

This part doesn't work

<?php> $order = ''; ?>

<form method="GET">
<select name="orderby" id="orderby">
<option value="<?php echo ($order = 'date'); ?>">Newest to Oldest</option>
<option value="<?php echo ($order = 'title'); ?>">Alphabetical</option>
<button type="submit">Apply</button>
</form>

And declaring the query where I pass the variable 'orderby' => $order

This part works (I'm getting a list of all the posts and changing the query manually works as well)

$wpb_all_query = new WP_Query(array('post_type'=>'post', 'posts_per_page'=>-1, 'order'=>'ASC', 'orderby'=> $order)); ?>

if ( $wpb_all_query->have_posts() ) :
<ul>


<?php while ( $wpb_all_query->have_posts() ) : $wpb_all_query->the_post(); ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>

</ul>
<?php endif;?>

How can I make this work?

Thank you in advance for the help!

Was it helpful?

Solution

Here I put orderby attributes as option values - date and title.

<form method="GET">
    <select name="orderby" id="orderby">
        <option value="date">Newest to Oldest</option>
        <option value="title">Alphabetical</option>
    <button type="submit">Apply</button>
<form>

On the same page you can recieve select value and set as orderby attribute

$wpb_all_query = new WP_Query(array(
    'post_type'=>'post', 
    'posts_per_page'=>-1, 
    'order'=>'ASC', 
    'orderby'=> esc_attr($_GET['orderby'])
); 

Use your loop to show posts

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top