我试图找到do_action和add_action的确切作用.我已经用add_action检查了但是对于do_action我正在尝试新的.这是我试过的.
function mainplugin_test() { $regularprice = 50; if(class_exists('rs_dynamic')) { $regularprice = 100; } // and doing further //like i echoing the regular price echo $regularprice; //It print 100 from this code }
现在我没有在主文件中放置少量代码,而是计划创建do_action以避免代码混乱问题.
function mainplugin_test() { $regularprice = 50; do_action('testinghook'); // and doing further //like i echoing the regular price echo $regularprice; //It should print 100 but it print 50 }
所以我创建了另一个函数来指出钩子就像
function anothertest() { if(class_exists('rs_dynamic')) { $regularprice = 100; } } add_action('testinghook','anothertest');
不知道如何将代码行添加到上面的函数可能有效的钩子中?按照我在测试环境中尝试过没有任何帮助.如果我理解正确的do_action更像是包含一个文件??? 如果没有,请告诉我.
谢谢.
之所以不打印100
,是因为函数$regularprice
内部anothertest()
是该函数的本地函数。$regularprice
父代中使用的变量mainplugin_test()
功能不一样的变量中使用的anothertest()
功能,它们是在单独的范围。
因此,您需要$regularprice
在全局范围内定义(不是一个好主意),或者可以将参数作为参数传递给do_action_ref_array
。该do_action_ref_array
是一样的do_action
,而不是它接受第二参数作为参数阵列。
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');
do_action
创建一个动作钩子,add_action
在调用该钩子时执行钩子函数.
例如,如果您在主题的页脚中添加以下内容:
do_action( 'my_footer_hook' );
您可以从functions.php或自定义插件回显该位置的内容:
add_action( 'my_footer_hook', 'my_footer_echo' ); function my_footer_echo(){ echo 'hello world'; }
您还可以将变量传递给钩子:
do_action( 'my_footer_hook', home_url( '/' ) );
您可以在回调函数中使用哪个:
add_action( 'my_footer_hook', 'my_footer_echo', 10, 1 ); function my_footer_echo( $url ){ echo "The home url is $url"; }
在您的情况下,您可能正在尝试根据条件过滤值.这就是过滤器钩子的用途:
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; }
参考
ADD_ACTION()
do_action()
的add_filter()
apply_filters()