(修改后的答案)
Gutenberg(或块编辑器)在处理页面/帖子(创建、更新等)时使用WordPress REST API,REST API将通过WP_REST_Posts_Controller::check_template()
当模板无效时,错误template is not one of
将被抛出。
正如我(最近)在this answer:
默认情况下,is_admin()
退货false
在REST API端点/URL上。例如,如果你在http://example.com/wp-json/wp/v2/posts
(或者您向该端点发出API请求),然后:
if ( is_admin() ) {
// code here does **not** run
}
这应该可以回答这个问题,你的
wpte_add_destination_templates
功能
is_admin()
检查失败,自定义模板未添加到有效/注册模板列表中;最终导致错误
template is not one of
.
可能的解决方案wp_loaded
和rest_api_init
add_action( \'wp_loaded\', array( $this, \'wpte_add_destination_templates\' ) ); // for admin requests
add_action( \'rest_api_init\', array( $this, \'wpte_add_destination_templates\' ) ); // for REST requests
在wpte_add_destination_templates
功能:
// If REST_REQUEST is defined (by WordPress) and is a TRUE, then it\'s a REST API request.
$is_rest_route = ( defined( \'REST_REQUEST\' ) && REST_REQUEST );
if (
( is_admin() && ! $is_rest_route ) || // admin and AJAX (via admin-ajax.php) requests
( ! is_admin() && $is_rest_route ) // REST requests only
) {
add_filter( \'theme_page_templates\', array( $this, \'wpte_filter_admin_page_templates\' ) );
}
或直接挂钩到theme_page_templates
//add_action( \'wp_loaded\', array( $this, \'wpte_add_destination_templates\' ) ); // remove
add_filter( \'theme_page_templates\', array( $this, \'wpte_filter_admin_page_templates\' ) );
然后你的
wpte_filter_admin_page_templates
将是:
function wpte_filter_admin_page_templates( $templates ) {
// If it\'s an admin or a REST API request, then filter the templates.
if ( is_admin() || ( defined( \'REST_REQUEST\' ) && REST_REQUEST ) ) {
$templates[\'templates/template-destination.php\'] = __( \'Destination Template\',\'\' );
} // else, do nothing (i.e. don\'t modify $templates)
return $templates;
}