1

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!

1 Answer 1

0

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

2
  • Love it, very smart and simple. Thx!
    – ergoProxy
    Apr 28, 2021 at 18:36
  • Do you have a php code snippet that I can you use to show a dropdown list with all post titles ordered alphabetical?
    – Willem
    Aug 6, 2021 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.