以下是我当前的操作钩子示例:它更改了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
我明白事实并非如此,但我不知道为什么。有人可以向我解释一下吗?
答案 0 :(得分:1)
在不知道所有内部工作的情况下,您可以将add_action()
视为简单的函数,该函数传递要在某个点调用的函数的名称。在您的代码中,add_action()
让系统知道在函数add_a_description()
到达wp_head
时调用它。
以下是代码如何工作的非常基本的示例:
// 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');
答案 1 :(得分: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
。
除非有条件地定义函数,否则在引用函数之前不需要定义函数。
关于wp_head
动作挂钩。 wp_head
函数位于wp-includes/general-template.php
如果您查看该功能,则会调用do_action('wp_head');
这是做什么的,它会检查用 wp_head 挂钩定义的所有操作和过滤器,它存储在全局变量 $ wp_actions
中如果wp_head中有一个钩子,它将使用 call_user_func_array
调用钩子函数希望这可以帮助你: - )