- Adding auth to WP REST API
- Using wp_filesystem
- The is_admin() tag
We can a permission callback to the custom REST route we are registering so it can be used to authenticate the requests.
It is important to secure endpoints that update the site data in any way using proper auth.
WP REST handles the authentication, we just have to enable it and use it.
register_rest_route(
'movie-library/v1',
'/rt-movie',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => array( $this, 'rt_movie_post_callback' ),
'permission_callback' => array( $this, 'rt_movie_permission_callback' ),
)
);
public function rt_movie_permission_callback( $request ) {
if ( current_user_can( 'edit_posts' ) ) {
return false;
}
return true;
}
Using wp file system
When doing any kind of file operations in the wp environment, we can use the wp file system, It is used by the core to perform updates and internal use.
To use the wp file system, first we have to initialize it and use the global $wp_filesystem object
if ( ! function_exists( 'WP_Filesystem' ) ) {
require_once ABSPATH . 'wp-admin/includes/file.php';
}
WP_Filesystem();
global $wp_filesystem;
Then we can use it to create files like this
$wp_filesystem->put_contents( 'myfile.txt, 'hello' );
is_admin() tag
This conditional is used to check if the current request is for the admin page, so we can use this to enable some functionality only in the admin back-end
It does not check if current user is admin or logged in, just if requested for admin page, returns true. Do not use this for authentication at all, use the capability and roles for that
Leave a Reply