wordpress

Sorting WordPress posts by custom date field where custom date field > current date


How can I get in WordPress 6 posts, ordered by custom date field and which have this custom date field > or = with current date. And how should I enter that custom_date? (what format).

EDIT: I try to do something like this:

$argsq = array(
          'cat' => 6,   
          'showposts' => 6,
          'meta_key'     => 'data-spectacol',
          'meta_value'   => date( "d-m-Y" ), 
          'meta_compare' => '>',
        );

And insert the data-spectacol meta field in a d-m-Y format in WordPress (like 15-5-2016) but I get older posts too, not only the posts after current date.


Solution

  • This should do it:

    $args = array(
        // the number of posts to show
        'showposts' => '6',
        // filter the posts with the date
        'meta_query' => array(
            'key'     => 'data-spectacol',
            'value'   => date( "Y-m-d" ), // change to how the date is stored
            'compare' => '>',
            'type' => 'DATE'
        ),
        // sort by the date field
        'orderby'   => 'meta_value_num',
        'meta_key'  => 'data-spectacol',
        'meta_type' => 'DATE'
    );
    $query = new WP_Query( $args );
    

    Make sure that the date is in a format that can be sorted correctly, this is usually done with Y-m-d or something similar.