简体   繁体   English

WordPress中的覆盖功能(带钩子)

[英]Override function (with hook) in wordpress

I have this situation: 我有这种情况:

parent theme: 父主题:

functions.php functions.php

require_once(dirname(__FILE__) . "/includes/theme-functions.php");
require_once(dirname(__FILE__) . "/includes/theme-hooks.php"); 

theme-function.php theme-function.php

function name_of_this_function() {
    // DO SOMETHING
}
add_action ('hook','name_of_this_function');

theme-hooks.php theme-hooks.php

function hook() {
    do_action('hook');
}

How can I override that action in my child functions.php given that mine is called before? 给定我的名字之前,我该如何在我的孩子的functions.php中覆盖该动作? I tried: 我试过了:

remove_action ('hook','name_of_this_function');

but of course this return false 但是当然,这返回false

I came to an answer after many attempts (miserably failed) and a lot of reading of documentation online. 经过多次尝试(非常失败)并在线阅读了大量文档后,我得到了答案。

The solution resides in the "after_setup_theme" hook. 解决方案位于“ after_setup_theme”挂钩中。

Before I was adding my actions "on top" of the parent's, meaning that i had two headers, two footers and so on. 在将动作添加到父项的“顶部”之前,这意味着我有两个页眉,两个页脚,依此类推。 Of course the problem was that my functions.php was not able to remove something that was not added yet. 当然,问题在于我的functions.php无法删除尚未添加的内容。

This was caused by wordpress behavior that runs functions.php of the child before the one of the parent theme. 这是由在父主题之一之前运行子项的functions.php的wordpress行为引起的。

The solution to this problem is to add a function after the setup of theme with a priority that force it to runs after the one of the parent. 解决此问题的方法是在设置主题之后添加功能,该功能具有优先级,以强制其在父项之一之后运行。 In this way ALL functions of the parent would be initialized (the after setup of parent is called as last function) and I would be able to remove some actions. 这样,将初始化父级的所有函数(将父级的后设置称为最后一个函数),并且我将能够删除某些操作。 This is the syntax: 这是语法:

add_action('after_setup_theme', 'my_setup', 3);
function my_setup(){
    /* CUSTOM FOOTER */
    remove_action('footer_hook','parent_site_info',99);
    add_action('footer_hook','site_info',99);
}

That solved the problem. 那解决了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM