How to Expire a Post Based on Meta Box custom field value

Support General How to Expire a Post Based on Meta Box custom field value

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #42191
    collinsonfamily@gmail.com[email protected]
    Participant

    I'm looking for aome help in automatically changing the status of custom posts to draft, based on a custom field date and time (datetimepicker). So when the date and time in that field is past, the post status changes to draft.

    Can anyone give me some help on how to achieve this?

    Thanks,

    #42200
    collinsonfamily@gmail.com[email protected]
    Participant

    OK, I've got this working with some more research on this forum. Here's my code:

    // expire exams on date field.
    if (!wp_next_scheduled('expire_exams')){
      wp_schedule_event(time(), 'hourly', 'expire_exams'); // this can be hourly, twicedaily, or daily
    }
    
    add_action('expire_exams', 'expire_exams_function');
    
    function expire_exams_function() {
        $today = date('Ymd');
        $args = array(
            'post_type' => array('exam'), // post types you want to check
            'posts_per_page' => -1 
        );
        $posts = get_posts($args);
        foreach($posts as $p){
            $expiredate = get_post_meta($p->ID, 'end_date', true ); // get the raw date from the db
            if ($expiredate) {
                if($expiredate < $today){
                    $postdata = array(
                        'ID' => $p->ID,
                        'post_status' => 'draft'
                    );
                    wp_update_post($postdata);
                }
            }
        }
    }

    I then used the WP Crontrol plugin to get more visibilty over the cron job.

    #42201
    PeterPeter
    Moderator

    Hello,

    You can use the action hook rwmb_{$field_id}_after_save_field and update the post status after saving the field value. Please read more in the documentation
    https://docs.metabox.io/actions/rwmb-after-save-field/

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.