WordPress’s REST API provides a flexible way to interact with your site’s data. However, there might be instances where certain endpoints can expose sensitive information or provide vectors for potential attacks. The following PHP snippet helps tighten security by removing specific endpoints from the WordPress REST API.
The Code
<?php
add_filter('rest_endpoints', function ($endpoints) {
// Unset user 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]+)']);
}
// Unset comments endpoints
if (isset($endpoints['/wp/v2/comments'])) {
unset($endpoints['/wp/v2/comments']);
}
if (isset($endpoints['/wp/v2/comments/(?P<id>[\d]+)'])) {
unset($endpoints['/wp/v2/comments/(?P<id>[\d]+)']);
}
return $endpoints;
});
This snippet should be placed in your theme’s functions.php file or a site-specific plugin.
How It Works
- The
rest_endpointsfilter allows you to modify the array of endpoints registered with the REST API. - The provided code checks for the existence of endpoints related to users and comments and removes them from the REST API if they are set.
- This helps to prevent unauthorized access to user and comment data through the API.
Why This Matters
- Privacy: User and comment endpoints can reveal personal data that shouldn’t be publicly accessible.
- Security: Removing these endpoints can reduce the risk of REST API abuse by malicious actors.
Customizing the Snippet
You can adjust the snippet to target additional endpoints that you may wish to remove based on the needs of your WordPress site.
Conclusion
By selectively disabling certain REST API endpoints, you can enhance the privacy and security of your WordPress website, protecting against unauthorized data access and potential exploitation. This approach is an important step in hardening your WordPress installation.

Leave a Reply