当前位置: 首页 » 笔记 » wordpress禁用REST API导致古腾堡编辑器发布文章出错问题正文

wordpress禁用REST API导致古腾堡编辑器发布文章出错问题

  • 零分
  • 2,042

wordpress禁用REST API,在function.php中加入以下代码:

add_filter("json_enabled", "__return_false");
add_filter("json_jsonp_enabled", "__return_false");
add_filter("rest_enabled", "__return_false");
add_filter("rest_jsonp_enabled", "__return_false");
remove_action("init", "rest_api_init");
remove_action("rest_api_init", "rest_api_default_filters", 10);
remove_action("parse_request", "rest_api_loaded");
remove_action("wp_head", "rest_output_link_wp_head", 10);
remove_action("template_redirect", "rest_output_link_header", 11);
remove_action("auth_cookie_malformed", "rest_cookie_collect_status");
remove_action("auth_cookie_expired", "rest_cookie_collect_status");
remove_action("auth_cookie_bad_username", "rest_cookie_collect_status");
remove_action("auth_cookie_bad_hash", "rest_cookie_collect_status");
remove_action("auth_cookie_valid", "rest_cookie_collect_status");
 
add_filter("rest_authentication_errors", function () {
    return new WP_Error("rest_disabled", __("The REST API on this site has been disabled."), ["status" => rest_authorization_required_code()]);
});

或者

// 屏蔽 REST API
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');

// 移除头部 wp-json 标签和 HTTP header 中的 link
remove_action('wp_head', 'rest_output_link_wp_head', 10 );
remove_action('template_redirect', 'rest_output_link_header', 11 );
add_filter( 'rest_authentication_errors', function( $access ) {
	return new WP_Error( 'rest_cannot_acess', 'REST API不再提供访问', array( 'status' => 403 ) );
});

但会出现一个问题,就是古腾堡编辑器在发布文章的时候,会提示JSON错误。

百度搜索了一番,无法找到合适的方法,下载了一些插件,复制里面的禁用代码,一样还是无法解决。

于是换了一种思路,既然是编辑器无法发布文章,那一定是因为有登录账号,大多数情况下。登录的都是管理员账号,就加另一个判断,非登录或者登录账号不是管理员,就禁用REST API,如果登录的是管理员,就取消禁用。

判断登录:is_user_logged_in(),判断管理员:current_user_can(‘manage_options’)

if(!is_user_logged_in() || !current_user_can('manage_options')){
//禁用代码
}

后台可以正常发布文章了。

声明:博客中如无特殊说明或标注的文章均为博客原创文章,部分文章来源互联网,如有侵犯您的版权,或者对零分博客发布的文章有异议,请来信告知删除、修改,如您有好的建议或者意见也可以来信,谢谢!

请TA喝杯水^_^ 如本文“对您有用”,欢迎随意打赏,让我们坚持创作! 请TA喝水