WordPress 钩子中的匿名函数 [英] Anonymous functions in WordPress hooks

查看:26
本文介绍了WordPress 钩子中的匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WordPress hooks 有两种使用方式:

WordPress hooks can be used in two ways:

  1. 使用回调函数名和合适的函数

  1. using callback function name and appropriate function

add_action( 'action_name', 'callback_function_name' );
function callback_function_name() {
    // do something
}

  • 使用匿名函数(闭包)

  • using anonymous function (closure)

    add_action( 'action_name', function() {
        // do something
    } );
    

  • WordPress 使用方式有什么不同吗?什么是首选方式,为什么?

    Is there any difference for WordPress what way to use? What is prefered way and why?

    推荐答案

    匿名函数的缺点是您无法使用 remove_action.

    The disadvantage of the anonymous function is that you're not able to remove the action with remove_action.

    重要提示:要删除挂钩,$function_to_remove$priority 参数必须在添加挂钩时匹配.这适用于过滤器和操作.删除失败时不会发出警告.

    Important: To remove a hook, the $function_to_remove and $priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.

    因为你没有定义function_to_remove,所以你不能删除它.

    Because you didn't define function_to_remove, you can't remove it.

    所以你永远不应该在其他人可能想要覆盖的插件或主题中使用它.

    So you should never use this inside plugins or themes that somebody else might want to overwrite.

    这篇关于WordPress 钩子中的匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆