我通过子主题扩展了父主题类:
add_action( 'after_setup_theme', function() {
class MyNewClass extends MyOldClass {
public function __construct() {
parent::__construct();
}
public function output() { //this function exists also in MyOldClass, echoing $this->args[ 'before' ] . "What's Up?" . $this->args[ 'after' ];
echo $this->args[ 'before' ] . "Hi There" . $this->args[ 'after' ];
}
}
$theClass = new MyNewClass;
}, 42 );
但它不会覆盖原始输出()。
如果我这样做
echo($theClass->output());
它确实打印了我想要的内容(>> Hi There<<),但是没有到位。
旧的输出()仍然在运行,新的输出不会覆盖它。
发生了什么?
答案 0 :(得分:1)
试试这段代码:
<?php
class MyNewClass extends MyOldClass {
public function __construct() {
add_action( 'after_setup_theme', array( $this, 'return_output' ) );
}
public function return_output() {
//this function exists also in MyOldClass, echoing $this->args[ 'before' ] . "What's Up?" . $this->args[ 'after' ];
echo $this->args[ 'before' ] . "Hi There" . $this->args[ 'after' ];
}
}
$theClass = new MyNewClass;
echo $theClass->return_output();
?>
或者在类中编写Hooks的正确方法在这里解释:https://developer.wordpress.org/reference/functions/add_action/