0

I have custom post type with meta values added by Advanced Custom Fields. I want to sort posts with get method by this meta and by post_date.

I make some code but it is works strange way - it didn't add opportunity to sort posts by meta, but just make any 'orderby' sorted by meta. So when I write in browser something like www.mysite.com/archive/?orderby=post_date it still sort it only by meta.

function my_pre_get_posts( $query ) {

    // do not modify queries in the admin
    if( is_admin() ) {

        return $query;

    }


    // only modify queries for 'text' post type
    if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'text' ) {

        // allow the url to alter the query
        if( isset($_GET['orderby']) ) {

            $query->set('orderby',  'meta_value_num');  
            $query->set('meta_key', 'text_date');
            $query->set('order', 'DESC'); 


        } 

    }

    // return
    return $query;

}
add_action('pre_get_posts', 'my_pre_get_posts');
0

You're not actually using the $_GET['orderby']-value anywhere. What you're doing in your code is ordering by the text_date-meta value, always. If you want to order by date by default, and when $_GET['orderby'] is set to default orderby-values or if $_GET['orderby_meta'] is set, order by those instead you need to do something like this:

if (isset($_GET['orderby']){
    $query->set('orderby', sanitize_key($_GET['orderby']);  
    $query->set('order', 'DESC'); 
} else if (isset($_GET['orderby_meta']){
    $query->set('orderby',  'meta_value_num');  
    $query->set('meta_key', 'text_date');
    $query->set('order', 'DESC'); 
}
  • Thanx for this answer. By default I want order by date, but i want to have opportunity to order them also by meta value. – Bidin Dec 9 '16 at 13:04
  • Alright – date ordering is probably default, so you can remove the else-statement from my answer, and that should allow you to order by a meta value where that is needed (for example text_date), if that's what you meant? – Emil Dec 9 '16 at 13:07
  • Nearly! Only last moment. So when i make something like orderby=title - wp thinks that i mean meta key "title" but not normal meaning of that variable. How can i handle with it? – Bidin Dec 9 '16 at 13:36
  • Take a look at the edited answer - you'll need to use different $_GET-variables for meta keys and for regular orderby-keys. – Emil Dec 9 '16 at 13:50
  • may be i can make some if statement only for "text_date" something like if (isset($_GET['orderby'] == 'text_date') ? – Bidin Dec 9 '16 at 14:50

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.