do_action和add_action如何工作?

Vig*_*ani 15 php wordpress wordpress-plugin

我试图找到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

}
Run Code Online (Sandbox Code Playgroud)

现在我没有在主文件中放置少量代码,而是计划创建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

    }
Run Code Online (Sandbox Code Playgroud)

所以我创建了另一个函数来指出钩子就像

function anothertest() {
if(class_exists('rs_dynamic')) {
$regularprice = 100;
}
}
add_action('testinghook','anothertest');
Run Code Online (Sandbox Code Playgroud)

不知道如何将代码行添加到上面的函数可能有效的钩子中?按照我在测试环境中尝试过没有任何帮助.如果我理解正确的do_action更像是包含一个文件??? 如果没有,请告诉我.

谢谢.

dig*_*ggy 27

do_action创建一个动作钩子,add_action在调用该钩子时执行钩子函数.

例如,如果您在主题的页脚中添加以下内容:

do_action( 'my_footer_hook' );
Run Code Online (Sandbox Code Playgroud)

您可以从functions.php或自定义插件回显该位置的内容:

add_action( 'my_footer_hook', 'my_footer_echo' );
function my_footer_echo(){
    echo 'hello world';
}
Run Code Online (Sandbox Code Playgroud)

您还可以将变量传递给钩子:

do_action( 'my_footer_hook', home_url( '/' ) );
Run Code Online (Sandbox Code Playgroud)

您可以在回调函数中使用哪个:

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

在您的情况下,您可能正在尝试根据条件过滤值.这就是过滤器钩子的用途:

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;
}
Run Code Online (Sandbox Code Playgroud)

参考

  • 如果您尝试修改返回值,过滤器是最佳选择。动作钩子通常用于打印/插入内容,或执行函数。 (2认同)
  • 不是反过来吗?“_`do_action` 创建一个动作挂钩,`add_action` 执行挂钩..._”这与您链接的页面相矛盾。 (2认同)

Rah*_*zir 6

之所以不打印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');
Run Code Online (Sandbox Code Playgroud)