正如Howdy\\u McGee和Tom J Nowell指出的那样,问题在于WordPress中动作的顺序和事件发生的顺序。
您可以在模板文件中自定义操作,
// header.php
do_action(\'my_custom_action\');
要针对这些操作,您应该将它们的回调添加到
functions.php
文件您可以使用
the conditional helper functions 如果只需要在某些模板上运行回调,请检查上下文。这里有几个例子,
// Do something on every template/view
add_action(\'my_custom_action\', \'my_global_header_function\');
// conditional checks directly in the callback
add_action(\'my_custom_action\', \'my_custom_action_callback\');
function my_custom_action_callback() {
// Blog page specific
if ( is_home() ) {
my_blog_header_function();
}
// Only pages
if ( is_page() ) {
my_page_header_function();
}
}
// conditional checks on earlier action
// more typical way to do this in my experience
add_action(\'template_redirect\', \'my_template_redirect_callback\');
function my_template_redirect_callback() {
// Do something on every template/view
add_action(\'my_custom_action\', \'my_global_header_function\');
// Blog specific function
if ( is_home() ) {
add_action(\'my_custom_action\', \'my_blog_header_function\');
}
// Only pages
if ( is_page() ) {
add_action(\'my_custom_action\', \'my_page_header_function\');
}
}
function my_global_header_function() {
echo \'This works everywhere\';
}
function my_blog_header_function() {
echo \'This the blog page\';
}
function my_page_header_function() {
echo \'This is a page\';
}
另外,在抄本上有一个很好的参考列表,列出了WordPress默认触发的不同操作,
Action Reference.