0

I want to add some buttons that will sort the post by name asc/desc etc. I want to use query in the link like this

http://domain.tld/?orderby=name&order=asc

Is this safe to use?

Are there rewrite rules i can use to change orderby=name to order-name and order=asc to ascending?

0

You could use rewrite rules but doing it the way you've put should be fine.

It's safe so long as you sanitize the query string.

Using add_query_arg() you can add a query to the end of your current URL, like this:

   $link = add_query_arg( 'orderby', 'name', get_permalink() );

You can then, for example, apply it to a button:

   <a href="<?php echo $link; ?>">Sort by name</a>

So now, when you click that link it will add 'orderby=name' to your URL. You could do this manually but add_query_arg() makes it easier and cleaner and there's also remove_query_arg() to help you too.

So now that we've changed the URL we now need do the ordering. I'm going to assume you're using the standard homepage query which is the most recent 10 posts and we're going to use pre_get_posts to complete the task. If you're not familiar with this then you should read up on it and see how you can exploit it, rather than creating secondary queries (if that is indeed what you're currently doing).

function wpse_142352_orderby( $query ) {

    // Don't do this in the admin and ONLY for the main loop
    if ( is_admin() || ! $query->is_main_query() )
        return;

    // Only on the frontpage
    if ( is_home() ) {

        // Safely get the orderby value
        $orderby = sanitize_key( $_GET['orderby'] );

        // If orderby is set then do it
        if (isset($orderby) {
              $query->set( 'orderby', $orderby );
              return;
        }
    }

}
add_action( 'pre_get_posts', 'wpse_142352_orderby', 1 );

That means now, instead of showing the 10 most recent posts, it will show the first (or last depending on if order = ASC or DESC) 10 in alphabetical order.

Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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