Are hooks called synchronously?

The do_action() and apply_filters() are both wrappers of the

WP_Hook::apply_filters()

method, that invokes the registered callbacks in sequential order (src).

Here’s a simple test:

Let’s define a callback wrapper:

$callback_gen = function( $seconds ) { 
    return function() use ( $seconds ) {
        sleep( $seconds ); 
        printf( '%s finished' . PHP_EOL, $seconds ); 
    };
};

Next we register the callbacks to the mytest action:

add_action( 'mytest', $callback_gen( 3 ) );
add_action( 'mytest', $callback_gen( 5 ) );
add_action( 'mytest', $callback_gen( 1 ) );

Then we invoke the callbacks and measure the time it takes:

$start = microtime( true );
do_action( 'mytest' );
$stop = microtime( true );

and display it with:

echo number_format( $stop - $start, 5 );

Here are outputs from 5 test runs:

3 finished 
5 finished 
1 finished 
9.00087

3 finished 
5 finished 
1 finished 
9.00076

3 finished 
5 finished 
1 finished 
9.00101

3 finished 
5 finished 
1 finished 
9.00072

3 finished 
5 finished 
1 finished 
9.00080

where the order is the same for each run, with total of c.a. 9 seconds, as expected for a sequential run order.

Leave a Comment