问题是,您正在从非静态方法内部调用静态方法。以下操作将起作用。
class theme_Rest_Routes extends WP_REST_Controller{
public static function init() {
$instance = new self();
add_action( \'rest_api_init\', array( $instance, \'register_routes\' ) );
}
public function register_routes() {
register_rest_route( \'theme/v1\', \'/menu/\', array(
\'methods\' => \'GET\',
\'callback\' => array( $this, \'theme_rest_menu\' ) )
);
}
public function theme_rest_menu( $request ) {
return wp_get_nav_menu_items( \'menu\' );
}
}
theme_Rest_Routes::init();
代码改进rest_api_init
从控制器类本身内部,而不是从外部类/函数调用它。类名也应该使用大写单词。如下所示:
function theme_register_rest_apis() {
$controller = new Theme_Rest_Routes();
$controller->register_routes();
}
add_action( \'rest_api_init\', \'theme_register_rest_apis\' );
class Theme_Rest_Routes extends WP_REST_Controller{
public function register_routes() {
register_rest_route( \'theme/v1\', \'/menu/\', array(
\'methods\' => \'GET\',
\'callback\' => array( $this, \'theme_rest_menu\' ) )
);
}
public function theme_rest_menu( $request ) {
return wp_get_nav_menu_items( \'menu\' );
}
}