skip to Main Content

I created a custom field ACF named "date_dexpiration" with format : d/m/Y H:i

When I create a new post with no expiration date, the field "date_dexpiration" is not fullfilled and stays empty.

I want in an archive (created with elementor posts widget) set a custom filter in order to hide all the posts with a date "date_dexpiration" < today.
I wrote this code inserted in function.php

add_action( 'elementor/query/filter_expiration_date', function( $query ) {
    $today = date('d/m/Y H:i');
    $meta_query = $query->get( 'meta_query' );
    $meta_query = [
        [       
        'key'       => 'date_dexpiration', 
        'value'     => $today,
        'compare'   => '>=',
        ]
    ];
    $query->set( 'meta_query', $meta_query );
} );

It doesn’t work:

  • all the posts with empty field "date_dexpiration" aren’t displayed
  • all the field with filled field "date_dexpiration" aren’t displayed

Can you help me please to debug this code.

2

Answers


  1. Chosen as BEST ANSWER

    Thank you for your answer. I had to change a bit the code you gave. Here is my last version:

    add_action( 'elementor/query/filter_expiration_date', function( $query ) {
            $today = date('Ymd');
            $meta_query = $query->get( 'meta_query' );
            $meta_query = [
                [       
                'key'       => 'date_dexpiration', 
                'value'     => $today,
                'type'      => 'DATE',
                'compare'   => '>=',
                ]
            ];
            $query->set( 'meta_query', $meta_query );
    } );
    

    It works fine when the ACF fieeld is fullfilled (for expired and not expired values), but not works when the field is not fullfilled or doesn't exist for a post. These posts are not displayed.

    I tried:

    if( get_field('date_dexpiration') ) ...
    

    but doesn't work!

    Do you know how to keep the first filter and had the other filter for all the non fullfilled items.

    Thank you again.


  2. ACF default format for date fields is Ymd so you need to convert $today to Ymd format. Try this below code.

    add_action( 'elementor/query/filter_filter_expiration_date', function( $query ) {
        $today = date('d/m/Y H:i');
        $today = date( 'Ymd', strtotime( $today ) );
        $meta_query = $query->get( 'meta_query' );
        $meta_query = [
            [       
            'key'       => 'date_dexpiration', 
            'value'     => $today,
            'compare'   => '>=',
            ]
        ];
        $query->set( 'meta_query', $meta_query );
    } );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search