0

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().

3
  • This doesn't make sense to me, but if you want to stop code from executing in a function as a certain point, you can add return, or you can wrap the code in a conditional Commented May 22, 2022 at 13:59
  • I meant that using add_action hook, how to stop the execution of test() function with contains do_action. In the above example, if $post_id == 2 , the echo $post_id; code should not run in test()
    – dc09
    Commented May 22, 2022 at 14:02
  • 1
    You can’t. You can use exit but that would stop absolutely everything else from continuing. Commented May 22, 2022 at 15:48

2 Answers 2

-1

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

-1

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');
});
2
  • 1
    Thanks for the info, a plugin I was using had the above code and I did not want to edit the core code of the plugin, hence was trying to figure out a way to achieve this via add_action
    – dc09
    Commented May 25, 2022 at 5:35
  • Yep. That's the best way to go about customising/extending a plugin - especially when the authors were kind enough to include filters and action hooks.
    – Ismail
    Commented May 25, 2022 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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