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!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0