Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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. :)

share|improve this question

1 Answer 1

up vote 0 down vote accepted

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);
share|improve this answer
    
I've tried something similar with $meta_query, it didn't work back then, but your code works perfectly, thanks a lot. :) –  Daniel May 31 at 12:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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