• Hi
    I have set up a custom post-type with custom meta boxes for dates – the format the data is saved in is Year-Month-Day (e.g.. 2013-07-27). I’m not using the WP post date.

    My query to retrieve posts is as follows:

    $args = array(
    'post_type' => 'listings','meta_key' => 'usp_startdate', 'orderby' => 'meta_value','order'=>'DESC');
    
    $query = new WP_Query($args);

    This works fine to retrieve all posts, however I am trying to find a way to ONLY get posts between specific dates/years. I know I can sort data once retrieved but is there a good way of doing this in the query?

    Any help would be appreciated

    Cheers.

Viewing 3 replies - 1 through 3 (of 3 total)
  • I think this will select all posts for the year 2012:

    $args = array(
       'post_type' => 'listings',
       'meta_key' => 'usp_startdate',
       'orderby' => 'meta_value',
       'order'=>'DESC',
       'meta_query' => array(
          'key' => 'usp_startdate',
          'value' => array( '2012-01-01', '2012-12-31'),
          'compare' => 'BETWEEN'
       )
    );
    
    $query = new WP_Query($args);
    Thread Starter otromundo

    (@otromundo)

    Thanks. I needed to wrap the meta_query in another array to get this working. Here’s the code.

    $args = array(
       'post_type' => 'listings',
       'meta_key' => 'usp_startdate',
       'orderby' => 'meta_value',
       'order'=>'DESC',
       'meta_query' => array(
            array(
    			'key' => 'usp_startdate',
    			'value'   => array( '2012-01-01', '2012-12-31'),
    			'compare' => 'BETWEEN'
    			)
    		)
      );
    
    $query = new WP_Query($args);

    Yeah, sorry about that.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Help with WP_Query’ is closed to new replies.