Search code examples
phpwordpresssortingcustom-wordpress-pagesquery-variables

Wordpress sorting posts by date and title using a dropdown


I'm trying to set up a drop-down 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

<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>
  </select>
</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!


Solution

  • So your html form would be something like this:

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

    Then check which option, user selected using isset and $_GET['orderby']. Then based on the value returned, you could set your custom query! So your custom query would be something like this:

    $custom_orderby = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : "";
    
    if(!empty($custom_orderby) && "title" == $custom_orderby):
      $custom_query = new WP_Query(array(
        'post_type'=>'post',
        'posts_per_page'=>-1,
        'orderby'=> "title",
        'order'=>'ASC',
        ));
    endif;
    
    if(!empty($custom_orderby) && "date" == $custom_orderby):
      $custom_query = new WP_Query(array(
        'post_type'=>'post',
        'posts_per_page'=>-1,
        'orderby'=> "date",
        'order'=>'DESC',
        ));
    endif;?>
    
    <ul>
    
    <?php while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endwhile; ?>
    
    </ul>