Trying to exclude custom posts based on date, while sorting by custom field

by Ray Gulick   Last Updated September 13, 2017 13:08 PM

I have a custom post type named "performance". I have a custom post query that orders posts by a custom field value (order-date). Now I want to exclude posts that have order-dates that are in the past. I would think I could use the same "order-date" value to compare against todays date to determine if a post should be shown, but I can't find an example that works with the ordering. Everything I've tried breaks the ordering.

This seems to work!

<?php
  $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
  $today = date('Y-m-d');
  query_posts(array(
    'post_type' => 'performance', 
    'posts_per_page' => 5, 
    'caller_get_posts' => 5, 
    'paged' => $paged,
    'meta_key' => 'order-date',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_query' => array(
      array(
        'key' => 'order-date',
        'meta-value' => $value,
        'value' => $today,
        'compare' => '>=',
        'type' => 'CHAR'
        )
      )
    ));
if (have_posts()) :
while (have_posts()) : the_post();
?>

Note that I defined "$today" and added it to the meta_array for comparison with the meta-value. The past-dated performance items disappeared from the list and everything looks like it should. Thanks to Brady for putting me on the right track.



Answers 2


You need to make use of meta_query http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

<?php
 $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
 query_posts(array(
 'post_type' => 'performance', 
 'posts_per_page' => 5, 
 'caller_get_posts' => 5, 
 'paged' => $paged,
 'meta_key' => 'order-date',
 'orderby' => 'meta_value',
 'order' => 'ASC',
    'meta_query' => array(
        array(
            'key' => 'order-date',
            'value' => $value,
            'compare' => '>=',
            'type' => 'CHAR'
        )
    )
 ));
if (have_posts()) :
while (have_posts()) : the_post();
?>
Brady
Brady
June 23, 2011 21:47 PM

s_per_page' => 5, 
 'caller_get_posts' => 5, 
 'paged' => $paged,
 'meta_key' => 'order-date',
 'orderby' => 'meta_v
test
test
September 13, 2017 12:27 PM

Related Questions


Display only one post each WEEK

Updated April 06, 2015 17:03 PM

Used with meta_query in query_posts works slowly

Updated January 08, 2017 08:03 AM


Order post by year DESC and month ASC

Updated March 06, 2017 00:08 AM

How to start with post number x?

Updated September 20, 2017 10:08 AM