WordPress.org

Ready to get started?Download WordPress

Forums

Help with WP_Query (4 posts)

  1. otromundo
    Member
    Posted 1 year ago #

    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.

  2. vtxyzzy
    Member
    Posted 1 year ago #

    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);
  3. otromundo
    Member
    Posted 1 year ago #

    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);
  4. vtxyzzy
    Member
    Posted 1 year ago #

    Yeah, sorry about that.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags