关于 php:如何在 wordpress 中从子主题扩展一个类?

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.)

有没有办法解决这个问题?


子主题在父主题之前加载,因此您需要在父主题加载后运行的挂钩中定义类,以便父主题类存在以进行扩展。 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