delete custom post based on custom field date

You have a date format mismatch here. You say your dates are saved as Y/m/d in your custom field, which is correct, but then you try to match this format to unix timestamp (which is the result from time()).

Date and time formats need to be in exactly the same format in order to match or to compare two different dates in a custom field, this is how custom fields work. There is no logic to know and no logic to convert and match different date/time formats, so you will need to manually make sure that everything matches up.

Instead of using time() to return the current date/time and using that as date/time comparison, you should use current_time( 'Y/m/d' ). Just a note, this is only possible as from WordPress 3.9

Just another note, we can simplify your function as follow, which will be faster and better for performance (NOTE: Requires PHP 5.4 at least)

function delete_expired_events_callback() 
{
    $args = [
        'post_type'      => 'esitykset',
        'posts_per_page' => -1,
        'fields'         => 'ids', //only get post id's
        'meta_query'     => [
            [
               'key'     => 'show_date',
               'value'   => current_time( 'Y/m/d' ),
               'compare' => '<'
            ]
        ]
    ];

    $events = get_posts( $args );

    if ( $events ) {
        // Loop through the post ID's and delete the post
        foreach ( $events as $id )
            wp_delete_post( $id );
    }
}

Leave a Comment