在父主题中添加动作挂钩以更轻松地自定义子主题

时间:2014-02-06 作者:Bobby

我想知道为什么没有人(还没找到)在主题的开头和结尾添加自定义挂钩function.php 用于主题开发。

我问这个问题的原因是,在制作子主题时,我必须覆盖一些默认设置,如父主题主主题中设置的图像大小function.php (否!function_exists 覆盖)。所以我在我孩子的function.php将被覆盖。

除了添加function_exists wrapper,我想到的解决方案就是添加一个do_action() 在函数的开头和结尾。php。但这是一种不好的做法吗?如果是,为什么?

我找不到任何答案,也找不到任何人在任何地方问这个问题。

1 个回复
最合适的回答,由SO网友:fuxia 整理而成

Code in a functions.php (or any file loaded by that file) should not run automatically, eg. when the file is included. All code should be bound to hooks.
That means, you don’t need a special action in the parent theme. The child theme can turn off all parent theme callbacks with remove_action() and remove_filter().

But you can make that easier for child theme authors by adding a custom action after you have registered the callbacks.

Example

Parent theme

namespace ParentTheme;
// register callbacks
add_action( \'after_setup_theme\', __NAMESPACE__ . \'\\setup_custom_background\' );
add_action( \'after_setup_theme\', __NAMESPACE__ . \'\\setup_custom_header\' );
add_filter( \'body_class\',        __NAMESPACE__ . \'\\enhance_body_class\' );

// provide an entry point
do_action( \'parent_theme_loaded\', __NAMESPACE__ );

Child theme

add_action( \'parent_theme_loaded\', function( $namespace )
{
    remove_action( \'after_setup_theme\', $namespace . \'\\setup_custom_header\' );
});

See also this similar example for outdated PHP versions.


If your parent theme ignores the principle of separation of concerns and mixes everything in just one or two setup functions, use a later priority and overwrite those calls:

Parent theme

add_action( \'after_setup_theme\', \'some_setup_function\' ); // priority = 10

Child theme

add_action( \'after_setup_theme\', \'fix_theme_setup\', 11 ); // priority = 11

function fix_theme_setup()
{
    remove_theme_support( \'post-formats\' );
    // more changes here
}
结束

相关推荐

Child-theme breaks site

所以,我有一个子主题,里面除了所需的CSS文件之外什么都没有。一旦我激活了这个儿童主题,我的整个网站就关闭了。最后我有两个问题:激活一个只有CSS的子主题怎么能破坏我的网站</我怎样才能回到我原来的主题</这些是网站给我的错误:Warning: require_once(/wp-content/themes/interio_child/admin/options-framework.php) [function.require-once]: 无法打开流:中没有此类文件或目录/wp-c