Is it possible to change the value of a custom field after X number of seconds has passed since it was modified?

For example, I have a checkbox that a user can check to say whether or not they are available. By default the box is unchecked and what I want to do is, 7200 seconds (2 hours) after a user has checked the box, revert it back to unchecked.

Is this possible?


You'll need two meta fields: the 'available' field, and a 'lastchecked' field that contains a Unix timestamp for when the box was checked.

Then, you can use wp_cron (assuming your site has enough traffic; but most sites will get at least one visit an hour; if not, you can always set up a regular cron to visit your site every hour) to run your reset.

Assuming the meta fields are named as above, and 'available' is 1 for yes, 0 for no:

function reset_available_meta() {
    $args = array(
        'post_type'  => 'post',
        'meta_query' => array(
                'key'     => 'lastchecked',
                'value'   =>  time() - ( 60 * 60 * 2 ), // 2 hours ago
                'compare' => '<='
        'posts_per_page' => -1

    $resetQ = new WP_Query( $args );

    while ( $resetQ->have_posts() ) {
        update_post_meta( get_the_ID(), 'available', '0' );

        //optional: update lastchecked so it's not included for the next call
        update_post_meta( get_the_ID(), 'lastchecked', time() );

wp_schedule_event(time(), 'hourly', 'reset_available_meta' ); 

Is this like an option you have saved to the database? If so you could use wp_schedule_event.

At the same time you save the option that the user is available, push a scheduled event in two hours to revert the option back.

edit: Also when reverting the option back, remember to unschedule the event.

Alternatively, you could save a timestamp when saving the availability and when you check if the person is available, if the timestamp is over 2 hours old, change them not to be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.