Skip to content

Instantly share code, notes, and snippets.

@shanebp
Forked from dexit/api.php
Created November 10, 2021 16:21
Show Gist options
  • Save shanebp/2cff2c791c6bf61a7f559e0e2e1c96a9 to your computer and use it in GitHub Desktop.
Save shanebp/2cff2c791c6bf61a7f559e0e2e1c96a9 to your computer and use it in GitHub Desktop.
Disable WordPress REST API endpoints
// Remove init rest routes
remove_action( 'rest_api_init', 'create_initial_rest_routes', 0 );
// Remove oembed rest routes
function remove_json_api () {
// Remove the REST API lines from the HTML Header
remove_action( 'wp_head', 'rest_output_link_wp_head', 10 );
remove_action( 'wp_head', 'wp_oembed_add_discovery_links', 10 );
// Remove the REST API endpoint.
remove_action( 'rest_api_init', 'wp_oembed_register_route' );
// Turn off oEmbed auto discovery.
add_filter( 'embed_oembed_discover', '__return_false' );
// Don't filter oEmbed results.
remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
// Remove oEmbed discovery links.
remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
// Remove oEmbed-specific JavaScript from the front-end and back-end.
remove_action( 'wp_head', 'wp_oembed_add_host_js' );
// Remove all embeds rewrite rules.
add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' );
}
add_action( 'after_setup_theme', 'remove_json_api' );
// Disable certain rest routes
add_filter( 'rest_endpoints', function( $endpoints ){
if ( isset( $endpoints['/wp/v2/users'] ) ) {
unset( $endpoints['/wp/v2/users'] );
}
if ( isset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] ) ) {
unset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] );
}
return $endpoints;
});
// And this snippet completely disable the REST API and shows {"code":"rest_disabled","message":"The REST API is disabled on this site."} when visiting http://yoursite.com/wp-json/
function disable_json_api () {
// Filters for WP-API version 1.x
add_filter('json_enabled', '__return_false');
add_filter('json_jsonp_enabled', '__return_false');
// Filters for WP-API version 2.x
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');
}
add_action( 'after_setup_theme', 'disable_json_api' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment