【问题标题】:How to extend a class from child theme in wordpress?如何在 wordpress 中从子主题扩展类?
【发布时间】:2019-07-19 23:30:31
【问题描述】:

我正在尝试扩展父主题中的类,但是当我尝试在 functions.php 文件中添加我的类时出现致命错误,说找不到父类。我的课是这样的:

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 文件中尝试过)并且它可以工作,但这不是我认为的正确方式。那么有没有合适的方法来做到这一点。我可以在法典中看到:

与 style.css 不同,子主题的 functions.php 没有 覆盖其父级的对应项。相反,它被加载到 除了父母的functions.php。 (具体是加载 就在父文件之前。)

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

【问题讨论】:

  • 父主题的类是可插拔的吗?意味着它在声明之前有if (! class_exists ( 'ParentClass' )) 包装器?
  • @shahin 不,它不可插入

标签: php wordpress wordpress-theming


【解决方案1】:

子主题在父主题之前加载,因此您需要在父主题加载后运行的挂钩中定义类,以便父主题类存在以进行扩展。 after_setup_theme 将是合乎逻辑的选择。

function mytheme_includes() {
    require_once get_theme_file_path( 'includes/class-my-class.php' );
}
add_action( 'after_setup_theme', 'mytheme_includes' );

感谢@jakept

【讨论】:

    猜你喜欢
    • 2018-03-22
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2011-02-14
    • 1970-01-01
    • 2017-04-16
    相关资源
    最近更新 更多