How do do_action and add_action work?

前端 未结 4 1375
执念已碎
执念已碎 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 18:55

    The reason it didn't print 100, because $regularprice within anothertest() function is local to that function. The variable $regularprice used in parent mainplugin_test() function is not same as the variable used in anothertest() function, they are in separate scope.

    So you need to either define the $regularprice in a global scope (which is not a good idea) or you can pass argument as a parameter to do_action_ref_array. The do_action_ref_array is the same as do_action instead it accepts second parameter as array of parameters.

    Passing as argument:

    function mainplugin_test() {
    
        $regularprice = 50;
        
        // passing as argument as reference
        do_action_ref_array('testinghook', array(&$regularprice));
    
        echo $regularprice; //It should print 100
    
    }
    
    // passing variable by reference
    function anothertest(&$regularprice) {
        if(class_exists('rs_dynamic')) {
            $regularprice = 100;
        }
    }
    // remain same
    add_action('testinghook','anothertest');
    

提交回复
热议问题