Possible to create a permalink to sort with meta_key?

I feel like I’ve been all around the web and back again looking for an answer to this and it’s really starting to grind my gears.

Not sure if this is the correct way to do it, but I want to add a query_posts array to a URL in the form of a query_arg. This is our query:

Read More
query_posts( array( 'meta_key' => 'rank', 'orderby' => 'meta_value_num', 'order' => 'DESC' , 'paged' => $paged,

How do I use add_query_arg to pass that to the URL so as to re-order the posts with that meta_key/query_posts array? I tried this, it doesn’t seem to change the order of the posts, there’s something I’m missing here.

<a href="<?php echo $by_rank;?>">  Rank </a>
     <?php $by_rank= esc_url(add_query_arg(array('meta_key' => 'rank',  'orderby' => 'meta_value_num', 'order' => 'DESC'))); ?>

The reason I want to add the query vars to the URL string is so users can sort posts on category pages based on the meta_key/meta_value. Sort of in a similar way to doing ?orderby=date, except with a meta_key.

This can be done, right? Because I’m seriously starting to think it’s not possible.

EDIT:- Tried this, this works to sort posts by ASC/DESC order, but not by the meta_key

<?php
$meta_key = (isset($_GET['meta_key'])) ?
            sanitize_text_field($_GET['meta_key']) : 'rank'; // use default value here ''

$orderby = (isset($_GET['orderby'])) ?
           sanitize_text_field($_GET['orderby']) : 'meta_value_num'; // use default value here ''

$order = (isset($_GET['order'])) ?
         sanitize_text_field($_GET['order']) : 'DESC'; // use default value here ''

$by_rank = esc_url(add_query_arg(array(
    'meta_key' => $meta_key,
    'orderby' => $orderby,
    'order' => $order
)));
?>
<a href="<?php echo $by_rank;?>">  Rank </a>

I should add that if I add the query_posts array directly into the page template it works just fine.

Related posts

Leave a Reply

1 comment

  1. What about something like that?

    function wpse139657_orderby(){
        if( isset($_GET['orderby']) ){
            $order = $_GET['order'] or 'DESC';
            set_query_var('orderby', 'meta_value_num');
            set_query_var('meta_key', $_GET['orderby']);
            set_query_var('order', $order);
        }
    }
    
    add_filter('pre_get_posts','wpse139657_orderby');
    

    In this way you can call your urls with a ?orderby=rank suffixed and it should do the trick. You can also have an optional order parameter, should you want to implement it.