Home › Forums › Back End › WordPress – Hide posts based on custom date field › Reply To: WordPress – Hide posts based on custom date field
If the date is a custom field, and you want to show posts based on the value of that custom field (= nothing to do with the publication date), you’ll have to filter by that using something like this:
$myposts = query_posts (array(
'orderby'=>'meta_value',
'meta_key'=>'my-custom-date-field',
'order'=>'asc'
)
);
while ( have_posts() ) : the_post();
echo '-'.the_title().'-'.get_field('my-custom-date-field').'<br>';
endwhile;
wp_reset_query();
This will just do a query of all your posts and sort them based on the value of the custom field “my-custom-date-field” (from old to more recent).
Next step: to only show posts that have a custom date value that comes after today’s date, you have to include a meta query within your query:
$myposts = query_posts (
array(
'orderby'=>'meta_value',
'meta_key'=>'my-custom-date-field',
'order'=>'asc',
'meta_query'=> array(
array(
'key'=>'my-custom-date-field',
'value'=>date('Ymd'),
'compare' => '>'
)
)
)
);
And then finally, in order to filter it out to show only posts that have a date value that is between today and 14 days from now:
$myposts = query_posts (
array(
'orderby'=>'meta_value',
'meta_key'=>'my-custom-date-field',
'order'=>'asc',
'meta_query'=> array(
array(
'key'=>'my-custom-date-field',
'value' => array(date('Ymd'), date('Ymd', strtotime('14 days'))),
'compare' => 'BETWEEN'
)
)
)
);
Make sure that the date format of your custom field matches the date format of your query (in this case Ymd).