WordPress.org

Support

Support » How-To and Troubleshooting » wp_query show posts by custom field after a date

wp_query show posts by custom field after a date

  • Hello all,

    I am using custom post types to create an events section. I’d like to show events which will be taking place in the future. The start date is stored in a custom field. I currently have:

    $args=array(
       'post_type' => 'event',
       'posts_per_page' => 5,
       'meta_key' => 'start_date',
       'orderby' => 'start_date',
       'paged' => $paged
    );
    $link = new WP_Query($args);

    This works great but returns results sorting by the start time so will show all previous events. I’d like to add a where start_date => current_date.

    Any help is much appreciated.

    Dave.

Viewing 1 replies (of 1 total)
  • You want to use the meta_compare and meta_value arguments to the query.

    You will need to format the current date to match what is in your custom fields. Assuming the format is yyyy-mm-dd, you would use something like this:

    $today = date('Y-m-d');
    $args=array(
       'post_type' => 'event',
       'posts_per_page' => 5,
       'meta_key' => 'start_date',
       'meta_compare' => '>',
       'meta_value' => $today,
       'orderby' => 'start_date',
       'paged' => $paged
    );
    $link = new WP_Query($args);
Viewing 1 replies (of 1 total)
  • The topic ‘wp_query show posts by custom field after a date’ is closed to new replies.