替换Custormizr主题的父动作

时间:2016-01-27 20:33:05

标签: php wordpress wordpress-theming

我创建了自己的孩子主题。一切都很好,除非我似乎无法取消注册。

$这是类TC_footer_main,以下代码位于__construct

add_action ( '__colophon'       , array( $this , 'tc_colophon_center_block' ), 20 );

我尝试了多次删除操作但没有成功。我只是想改变/删除页脚:

remove_action( '__colophon' , 'tc_colophon_center_block' , 55);

remove_action( '__colophon' , array('TC_footer_main','tc_colophon_center_block') , 55);

我也试过

remove_action( '__colophon' , TC_footer_main::$instance->tc_colophon_center_block() , 55);

但由于我的TC_footer_main文件运行时未加载functions.php,因此引发了错误。

3 个答案:

答案 0 :(得分:3)

为了您的目的,在function.php中添加以下代码。它会在after_setup_theme钩子上调用。

// replace parent function
function child_theme_function () {
    // your code goes here
 }

function my_theme_setup () {
    remove_action( '__colophon', 'tc_colophon_center_block', 1000 );
    add_action( '__colophon', 'child_theme_function', 1000 );
}
add_action( 'after_setup_theme', 'my_theme_setup' );

您也可以尝试覆盖子类中的父类,如下所述:https://thethemefoundry.com/tutorials/advanced-customization-replacing-theme-functions/

答案 1 :(得分:3)

  

我只是想更改/删除页脚:

我认为你修改tc_colophon_center_block()方法的输出比使用它更复杂。

只需使用tc_credits_display过滤器:

add_filter( 'tc_credits_display', function( $html )
{
    // Modify output to your needs!
    return $html;
} );

根据您的需要修改该块。

要完全删除输出(如果允许),只需使用:

add_filter( 'tc_credits_display', '__return_null', PHP_INT_MAX );

您可以进一步访问以下过滤器:

  • tc_copyright_link
  • tc_credit_link
  • tc_wp_powered

可供选择。

那就是它!

答案 2 :(得分:2)

你不是太遥远......你可能遇到的一个问题是你在父主题添加之前试图删除钩子......这个类可以在以后阶段初始化......

我不太确定你的钩子何时运行,但希望它在init之后

 add_action('init', 'remove_parent_hook');

 function remove_parent_hook(){
      remove_action( '__colophon' , array('TC_footer_main','tc_colophon_center_block') , 20); // needs to be the same priority
 }
显然你现在可以为你的新功能添加一个动作。

有一种情况是添加了匿名函数,通常在尝试删除钩子函数时会忽略&$this的重要性。这是一个痛苦,因为wp会将随机字符串指定为键名称&函数的函数名称,每次都不同,因此无法猜到。但我们可以在密钥中搜索函数名称,这样就可以了。

    function remove_anon_hk($hook, $function, $priority=10 ){

        global $wp_filter;

        $hooks= $wp_filter[$hook][$priority];

        if(empty ($hooks))
            return;

        foreach($hooks as $hk=>$data):
            if(stripos($hk, $function) !== false ){
                unset($wp_filter[$hook][$priority][$hk]);
            }
        endforeach;
    }


    add_action('init', function(){
        remove_anon_hk('__colophon', 'tc_colophon_center_block');
    });