I’ve seen similar questions and solutions, but so far I couldn’t apply it to my code.

The following code (functions.php) works perfectly fine:

   if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'turniere' )
{
    $query->set('orderby', 'meta_value_num');  
    $query->set('meta_key', 'date_start');  
    $query->set('order', 'ASC');

}  

Now I want to add a sort of date range. This is the “best” I’ve got so far:

if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'turniere' )
{
    $query->set('orderby', 'meta_value_num');  
    $query->set('meta_key', 'date_start');  
    $query->set('order', 'ASC');
    $query->set('meta_value', '20140520');
    $query->set('compare', '>=');
    $query->set('type', 'NUMERIC');
}   

But it doesn’t work, the page just says “no posts available”.

I’ve tried different combinations of each parameter (meta_value with or without ‘, different compare methods and every possible type).

‘date_start’ is stored as yyyymmdd. I use the plugin “advanced custom fields” to set the date in each post.

Any help is much appreciated. 🙂

1 Answer
1

I think it’s mainly because of the type parameter. You are probably looking for meta_query. Take a look at the following example from the codex:

$args = array(
   'post_type' => 'my_custom_post_type',
   'meta_key' => 'age',
   'orderby' => 'meta_value_num',
   'order' => 'ASC',
   'meta_query' => array(
       array(
           'key' => 'age',
           'value' => array(3, 4),
           'compare' => 'IN',
       )
   )
 );
 $query = new WP_Query($args);

I’m not 100% sure how to add a meta_query using $query->set, but you should be able to do the following:

$meta_query = array(
    array(
        'key' => 'date_start',
        'value' => '20140520',
        'compare' => '>=',
        'type' => 'NUMERIC'
    )
);

$query->set('orderby', 'meta_value_num');  
$query->set('meta_key', 'date_start');  
$query->set('order', 'ASC');
$query->set('meta_query', $meta_query);

Leave a Reply

Your email address will not be published. Required fields are marked *