【问题标题】:Understanding how WordPress hooks are called了解如何调用 WordPress 挂钩
【发布时间】:2013-12-10 16:17:00
【问题描述】:

这是我当前的动作挂钩示例:它更改了 HTML 页面的元描述。

add_action( 'wp_head', 'add_a_description' );

  function add_a_description () {
    echo '<meta name="description" content=" This is new content" />' . "
";

  } // End example

现在对我来说(我有一些基本的 PHP 知识,仅此而已),看起来该函数在创建之前就已被调用。我的直觉告诉我它应该是这样的:

      function add_a_description () {
        echo '<meta name="description" content=" This is new content" />' . "
    ";}

  add_action( 'wp_head', 'add_a_description' );  // End example

我知道情况并非如此,但我不知道为什么。谁能给我解释一下?

【问题讨论】:

    标签: php wordpress wordpress-theming


    【解决方案1】:

    无论你在哪里编写动作钩子都可以工作:

    add_action( 'wp_head', 'add_a_description' );
    
    function add_a_description () {
        echo '<meta name="description" content=" This is new content" />' . "";
    } 
    

    和

    function add_a_description () {
        echo '<meta name="description" content=" This is new content" />' . "";
    } 
    
    add_action( 'wp_head', 'add_a_description' );  // End example
    

    这两个都可以。在哪里声明函数并不重要,唯一的问题是函数应该包含在脚本中。

    这是因为whole file is first parsed and then executed。

    来自PHP Manual

    函数在被引用之前不需要定义,除非函数是有条件定义的。

    关于wp_head 动作钩子。 wp_head 函数位于 wp-includes/general-template.php 中

    如果您查看该函数,它将调用do_action('wp_head');

    它的作用是,它将检查所有使用 wp_head 挂钩定义的操作和过滤器,这些挂钩存储在全局变量 $wp_actions

    中

    如果 wp_head 有一个钩子,它将使用 call_user_func_array

    调用钩子函数

    希望这对你有帮助:-)

    【讨论】:

    • 许多其他语言是否允许以任何一种方式定义函数?
    • 我认为在 c、c++ 中你不能这样做。您需要在使用之前声明该函数或进行前向声明。我不确定其他语言。我认为大多数人都支持
    【解决方案2】:

    在不了解所有内部工作原理的情况下,您可以将add_action() 视为简单函数,它传递要在某个点调用的函数的名称。在您的代码中,add_action() 让系统知道在到达wp_head 点时调用函数add_a_description()。

    这是代码工作原理的一个非常基本的示例:

    // Start of example system
    $actions = array();
    
    function add_action($point, $name) {
      global $actions;
      $actions[$point][] = $name;
    }
    
    function run($point) {
      global $actions;
      foreach ($actions[$point] as $name)
        $name();
    }
    // End of example system
    
    // Start of example plugin / theme function
    add_action('wp_head', 'alert');
    function alert() {
      echo 'hello';
    }
    // End of example plugin / theme function
    
    // At point wp_head
    run('wp_head');
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 2014-03-03
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多