Created
February 9, 2021 22:04
-
-
Save smwoll/e28ea34b703dca6287482a46d9a314f0 to your computer and use it in GitHub Desktop.
Simple MU plugin to prevent WordPress REST API access without login
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Plugin Name: WP REST API Login Filter | |
* Plugin URI: https://skyland.dev | |
* Description: Disables the WP rest API without login. | |
* Version: 1 | |
* Author: Sky | |
* Author URI: https://skyland.dev | |
* | |
*/ | |
add_filter('rest_authentication_errors', function ($result) { | |
// If a previous authentication check was applied, | |
// pass that result along without modification. | |
if (true === $result || is_wp_error($result)) { | |
return $result; | |
} | |
// No authentication has been performed yet. | |
// Return an error if user is not logged in. | |
if (!is_user_logged_in()) { | |
return new WP_Error( | |
'rest_not_logged_in', | |
__('No way! You are not currently logged in.'), | |
array('status' => 401) | |
); | |
} | |
// Our custom authentication check should have no effect | |
// on logged-in requests | |
return $result; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment