I have an expiry date ACF field 'post_end_date'
which has been applied to multiple post types, including 'post'
.
I'm trying to filter out any posts, across the entire site, where today's date is greater than the value 'post_end_date'
; in other words the post has expired. I've checked that 'post_end_date'
value returns a number in the same format as date('Ymd')
. e.g.
echo date('Ymd'); // returns 20161128 for today
echo get_field('post_end_date'); // returns 20161127 for yesterday
I figured the best way would be to just do a numerical comparison between today's date and 'post_end_date'
value.
This is my code:
function expiry_filter($query) {
if( !is_admin() && $query->is_main_query() ) :
$today = $expire = date('Ymd');
if ( get_field('post_end_date') ) :
$expire = get_field('post_end_date');
endif;
$query->set( 'meta_query', array(
array(
'key' => $expire,
'value' => $today,
'compare' => '<',
'type' => 'NUMERIC'
)
));
endif;
}
add_action( 'pre_get_posts', 'expiry_filter' );
At this point, I was just trying to get it to work for the 'post'
post type. I have checked that I haven't used the wrong 'compare' operator. I've tried with and without the $query->is_main_query()
conditional.
The result I'm getting with the code above is ALL posts are being filtered out.
Can someone suggest what I might be doing wrong here?
Thanks in advance.
'key' => $expire
will result in'key' => 20161128
or something. Shouldn't it be'key' => 'post_end_date'
?>=
should to the trick. Have you checked your values?get_field
will refer to the current post which can lead to unexpected results as you hook in the main query. So maybe there is no post from today?post_end_date
is not set? Or do I do anif ( get_field('post_end_date') ):
around the$query->set
? If you submit as an answer, I will mark your reply as the answer.