How to extend a class from child theme in wordpress?
我正在尝试扩展父主题中的类,但是当我尝试在 functions.php 文件中添加我的类时出现致命错误,说找不到父类。我的课是这样的:
1
2 3 4 5 6 |
class MyClasss extends ParentTheme_Templates {
public static function header() { $type = ParentTheme_Global::instance()->get_header_type(); get_template_part( ‘mycomponents/headers/header’, $type ); |
但是我可以在我的模板文件中为我的类使用相同的代码(我在 header.php 文件中尝试过)并且它可以工作,但这不是我认为的正确方式。那么有没有合适的方法来做到这一点。我可以在法典中看到:
Unlike style.css, the functions.php of a child theme does not
override its counterpart from the parent. Instead, it is loaded in
addition to the parent’s functions.php. (Specifically, it is loaded
right before the parent’s file.)
有没有办法解决这个问题?
- 父主题类是可插拔的吗?意味着它在声明之前有 if (! class_exists ( ParentClass )) package器吗?
- @shahin 不,它不可插入
子主题在父主题之前加载,因此您需要在父主题加载后运行的挂钩中定义类,以便父主题类存在以进行扩展。 after_setup_theme 是合乎逻辑的选择。
1
2 3 4 |
function mytheme_includes() {
require_once get_theme_file_path( ‘includes/class-my-class.php’ ); } add_action( ‘after_setup_theme’, ‘mytheme_includes’ ); |
感谢@jakept
来源:https://www.codenong.com/51860858/