简体   繁体   中英

ACF - How do I exclude posts older than a year from relationship field?

I am using ACF Pro. I have a filter setup that tells ACF only to show posts that are published.

function acf_relationship_filter( $args, $field, $post_id ) {
    $args['post_status'] = array('publish');
    return $args;
}

add_filter('acf/fields/relationship/query/name=featured_items', 'acf_relationship_filter', 10, 3);

This works just fine. However, I'd like to extend this function so that only posts made in the last year are shown; older posts should therefore be excluded.

Anyone have ideas on how to do this?

I need to somehow apply the following test in the filter:

strtotime( $args['post_date'] ) > strtotime('-365 day');

Comparing the result of this on $args['post_date'] wont work of course because I'd be comparing a boolean result to a date string.

Thanks!


SOULTION:

I figured this out for anyone who might come across this same requirement.

Simply use $args['date_query'] .

function acf_relationship_filter( $args, $field, $post_id ) {

    $args['post_status'] = array('publish');
    $args['date_query'] = array(
        'after' => date('Y-m-d G:i:s', strtotime('-1 year')),
        'inclusive' => true
    );

    return $args;

}

add_filter('acf/fields/relationship/query/name=featured_items', 'acf_relationship_filter', 10, 3);

This will only show the posts that were made after a year ago from today.

Hope it helps someone out there!

WP Docs on date parameters for WP_Query: http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

If these are arguments to WP_Query , then you could try the date_query input argument:

$args['date_query'] = [
    [
        'after'     => '1 year ago', // <-- your strtotime string
        'inclusive' => true,
    ]
];

within your callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM