WordPress 4.7 以上版本禁用 wp-json

wp rest api

WP REST API

WordPress 4.4更新新增了REST API功能,通过REST API可以很轻松的获取网站的数据,应用于其他网站或者手机APP,但是并不是每个人都需要这个功能,并且不想在head里面输出wp-json链接,下面介绍禁用REST API或者说移除head里面wp-json链接的方法。

适用于WordPress 4.7 以下的方法

网上有禁用wp-json的代码以及移除头部wp-json的代码:

//移除wp-json链接
add_filter( 'rest_enabled', '_return_false' );
add_filter( 'rest_jsonp_enabled', '_return_false' );
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );

但是以上方法适用于WordPress 4.7以下的版本,而对于WordPress 4.7以上的版本不起作用。

WordPress 4.7版本不建议使用rest_enabled

升级后访问wp-json页面有如下提示

自4.7.0版本起,已不建议使用rest_enabled,请换用rest_authentication_errors。 REST API不再能被完全禁用,不过您可以用“rest_authentication_errors”过滤器来限制对该API的访问

以下代码可以完全禁用wp-json功能,适用于WordPress 4.7 以上版本,不需要依赖于任何插件:

/**
* 完全禁用wp-json
*
* @author 智慧宫
* @link https://lerm.net
*/
function lerm_disable_rest_api( $access ) {
	return new WP_Error(
		'Stop!',
		'Soooooryyyy',
		array(
			'status' => 403,
		)
	);
}
add_filter( 'rest_authentication_errors', 'lerm_disable_rest_api' );
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );

发表评论

游客欢迎您123

“WordPress 4.7 以上版本禁用 wp-json” 有 2条评论