• Hi all!

    I have a custom post called ‘discounts’ with a custom field ‘coupon_expiry’. I’d like posts to get automatically deleted on their expiry date.

    I’ve added the below code to my functions.php file, but it doesn’t seem to be working.

    Does anyone have any ideas how I can achieve this?

    current code –

    // Automatically delete coupons
    // Schedule the event on plugin activation or theme activation
    register_activation_hook( __FILE__, 'schedule_delete_expired_posts_event' );
    function schedule_delete_expired_posts_event() {
        if ( ! wp_next_scheduled( 'delete_expired_posts_event' ) ) {
            // Schedule the event to run daily at midnight (adjust the time as needed)
            wp_schedule_event( strtotime( 'midnight' ), 'daily', 'delete_expired_posts_event' );
        }
    }
    
    // Unschedule the event on plugin deactivation or theme deactivation
    register_deactivation_hook( __FILE__, 'unschedule_delete_expired_posts_event' );
    function unschedule_delete_expired_posts_event() {
        // Unscheduling the event will prevent it from running after plugin or theme deactivation
        wp_clear_scheduled_hook( 'delete_expired_posts_event' );
    }
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Scheduling an event is a reasonable approach. If it’s not working, it’s likely due to delete_expired_posts_event(). If you called it directly outside of a scheduled event (from “init” action for example), does it work properly?

    You might add an error_log() call to the function so you can easily confirm of the scheduled event actually called your callback or not.

    FWIW, some installations seem to have difficulty with wp-cron events. Some prefer to implement true server CRON to accomplish scheduled tasks.

Viewing 1 replies (of 1 total)
  • The topic ‘Auto delete a post based on custom field’ is closed to new replies.