How do do_action and add_action work?

前端 未结 4 1378
执念已碎
执念已碎 2020-12-14 18:42

I am trying to find what exactly do_action and add_action works. I already examine with add_action but for do_action i am trying as new now. This what i tried.



        
4条回答
  •  遥遥无期
    2020-12-14 19:12

    do_action creates an action hook, add_action executes hooked functions when that hook is called.

    For example, if you add the following in your theme's footer:

    do_action( 'my_footer_hook' );
    

    You can echo content at that location from functions.php or a custom plugin:

    add_action( 'my_footer_hook', 'my_footer_echo' );
    function my_footer_echo(){
        echo 'hello world';
    }
    

    You can also pass variables to a hook:

    do_action( 'my_footer_hook', home_url( '/' ) );
    

    Which you can use in the callback function:

    add_action( 'my_footer_hook', 'my_footer_echo', 10, 1 );
    function my_footer_echo( $url ){
        echo "The home url is $url";
    }
    

    In your case, you're probably trying to filter the value based on a condition. That's what filter hooks are for:

    function mainplugin_test() {
        echo apply_filters( 'my_price_filter', 50 );
    }
    
    add_filter( 'my_price_filter', 'modify_price', 10, 1 );
    function modify_price( $value ) {
        if( class_exists( 'rs_dynamic' ) )
            $value = 100;
        return $value;
    }
    

    Reference

    • add_action()
    • do_action()
    • add_filter()
    • apply_filters()

提交回复
热议问题