Search code examples
phpwordpressaggregatedebouncingpost-meta

Debounce Wordpress action hook (or any other PHP function)


I have a Wordpress plugin which sends post data after a post/postmeta change occurs.

The problem is that there can be very many postmeta changes on a busy Wordpress site, so I'd like to debounce/throttle/aggregate the meta updates to a single POST call, wrapped in a 1 second period.

Don't know how to approach this one, as I've been using async languages for some time now, and couldn't find a setTimeout equivalent for PHP.
Any shareable ideas?

add_action( 'updated_post_meta', 'a3_updated_post_meta', 10, 4 );

function a3_updated_post_meta($meta_id, $post_id, $meta_key, $meta_value){
    global $wpdb;
    global $a3_types_to_send;

    a3_write_log('---> u p d a t e d  post  m e t a');

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    $mongo_dest_address = 'http://localhost:8080/admin/dirty';
    $reason = 'edit_meta';

    $dirty_post_ids = get_option('a3_dirty_post_ids');

    if(! is_array($dirty_post_ids) ){
        $dirty_post_ids = array();
    }    

    $dirty_post_ids[] = (int) $post_id;

    update_option('a3_dirty_post_ids', array_unique($dirty_post_ids));    

    $object_type = $wpdb->get_var( $wpdb->prepare("select post_type from $wpdb->posts where ID = %d", $post_id) );

    if(in_array($object_type, $a3_types_to_send)){
        a3_send_post_trans($post_id, $reason);  
    }            
}

Solution

  • There is no straightforward way to do so in PHP. What I would propose to you is to explore other ideas like:

    A) stop firing those actions and running cron script every x seconds (simple php script which is being fired by server in specific interval which would process posts) B) firing actions in similar way as you do it now and putting the posts into a specific queue (it could have any forms depending on your expertise, from simplest ones to for example RabbitMQ). Afterwards you would have to create queueHandler script (in a similar way as in first point) which would process your posts from the queue.