WordPress.org

Ready to get started?Download WordPress

Forums

Orderby code not working (2 posts)

  1. admin@norris-stevens.com
    Member
    Posted 1 year ago #

    I want to allow users to order a posts list through a drop-down menu, but I can't get the following code to work.

    <div class="sort">
         <select onclick="if (this.value) { document.location = this.value; }">
            <option value="" selected="selected">Sort by</option>
            <option value="<?php echo $short_page_url; ?>?orderby=title&order=ASC">Titles Z-A</option>
            <option value="<?php echo $short_page_url; ?>?orderby=title&order=DESC">Titles A-Z</option>
         </select>
    </div>
    
    <?php $posts = get_posts("numberposts=20&cat=30"); foreach ($posts as $post) : setup_postdata($post); ?>
    
    CONTENT GOES HERE
    
    <?php endforeach; ?>

    Any help would be appreciated.

  2. vtxyzzy
    Member
    Posted 1 year ago #

    First, you have the order values reversed. Z-A should be DESC and A-Z should be ASC.

    Then, change this:

    <?php $posts = get_posts("numberposts=20&cat=30"); foreach ($posts as $post) : setup_postdata($post); ?>

    to this:

    <?php
    $orderby = (isset($_GET['orderby'])) ? "&orderby={$_GET['orderby']}" : '';
    $order = (isset($_GET['order'])) ? "&order={$_GET['order']}" : '';
    
    $posts = get_posts("numberposts=20&cat=32$orderby$order"); foreach ($posts as $post) : setup_postdata($post); ?>

Topic Closed

This topic has been closed to new replies.

About this Topic