How to stop execution of a function via add_action hook?

I have the following functions:

function test($post_id){

do_action('test_action',$post_id);

echo $post_id;

}

add_action('test_action',function($post_id){

if ( $post_id == 2 ) //Stop test function execution

}

Using the function hooked to add_action, how to stop the execution of test() function without adding any code to test(). In the above example, if $post_id == 2 , the echo $post_id; code should not run in test().

Topic actions hooks Wordpress

Category Web


You have both registered and called action hooks, did you know you could do the same with filters? This answer uses a filter to call a return; statement as the community suggested, to do an early return and stop executing the rest of test function body (echo in your case).

function test($post_id)
{
    do_action('test_action', $post_id);

    if ( apply_filters('wpse_405965_stop_execution', false) )
        return;

    echo $post_id;
}

add_action('test_action', function($post_id)
{
    if ( $post_id == 2 ) // Stop test function execution
        add_filter('wpse_405965_stop_execution', '__return_true');
});

The usual way to add an action hook is more like this:

// ... some other code
do_action( 'my_action', $post_id );

// ...elsewhere
add_action( 'my_action', 'wpse405965_function' );
/**
 * Function hooked to my_action
 *
 * @param int $post_id The post ID.
 */
function wpse405965_function( $post_id ) {
    if ( 2 !== $post_id ) {
        echo $post_id;
    }
}

The way you've wrapped the do_action() inside a function confuses me. It seems extraneous.

Reference

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.