1

I have a custom field called "value_date" where add a date e.g yyyy/mm/dd

The idea is sort the upcoming dates first in the loop, is possible?

I used a template for custom post taxonomy-event-date.php and this is code in the function, It doesn't work.

Functions.php

add_action('pre_get_posts','search_filter');
function search_filter($query){
    if ( !is_admin() && $query->
is_tax( 'event', 'date' ) ) {
        $today = date( 'Y-m-d' );
        $query->set('post_status', 'publish');
        $query->set('meta_value', $today);
        $query->set('meta_key', 'value_date');
        $query->set('orderby', 'meta_value_num');
        $query->set('order', 'ASC');
    }
}
  • 1
    It's possible, look around for pre_get_posts questions, however- your date format is incorrect and will need to be changed to yyyy/mm/dd to sort correctly. – Milo Apr 19 '17 at 17:09
1

Yes, You can call action "pre_get_posts".

add_action('pre_get_posts','search_filter');

You can add parameter :

$args = array(
  'post_status'       => 'publish',
  'posts_per_page'    => 6,
  'paged'             => $paged,
  'meta_key'          => 'event_date',
  'orderby'           => 'meta_value_num',
  'order'             => 'ASC'
);

You can use above parameter e.g. :

function search_filter($query){
    if ( !is_admin() && $query->is_main_query() ) {
        $query->set('post_status', 'publish');
        $query->set('meta_key', 'event_date');
        $query->set('orderby', 'meta_value_num');
        $query->set('order', 'ASC');
    }
}
  • This can be done in the same default main query of the template taxonomy-event-date.php ? – Max Apr 19 '17 at 18:10
  • It will work by default on taxonomy-event-date.php but you need to validate for specific page taxonomy-event-date in search filter. Otherwise it will load for all pages. – Punit Patel Apr 20 '17 at 3:53
  • Thanks Punit!, With the above query does not work because the page appear 404 error when going to the second page – Max Apr 22 '17 at 21:50
  • Hi @Max You need to add $query->set('paged', $page) in search_filter function here you will get $page value by $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; – Punit Patel Apr 23 '17 at 4:47
  • Hi @punit-patel It doesn't work, check my edit – Max May 16 '17 at 17:54

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.