do_action和add_action如何工作?

 小菜刀丶 发布于 2022-12-12 18:49

我试图找到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更像是包含一个文件??? 如果没有,请告诉我.

谢谢.

2 个回答
  • 之所以不打印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');
    

    2022-12-12 18:50 回答
  • 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()

    2022-12-12 18:52 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有