Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellenmace/242a53ce2a583004ee5687cde0b5d2aa to your computer and use it in GitHub Desktop.
Save kellenmace/242a53ce2a583004ee5687cde0b5d2aa to your computer and use it in GitHub Desktop.
Create a custom WordPress REST API controller class for the Page post type.
<?php
/**
* Class to access pages via the REST API.
*
* @author Kellen Mace
*
* @see WP_REST_Posts_Controller
* @see WP_REST_Controller
*/
class KM_REST_Pages_Controller extends WP_REST_Posts_Controller {
/**
* Checks if a given request has access to read a page.
*
* @param WP_REST_Request $request Full details about the request.
* @return bool|WP_Error True if the request has read access for the item, WP_Error object otherwise.
*/
public function get_item_permissions_check( $request ) {
// Here we're checking a _is_protected_content post meta value
// to determine whether this page is considered protected content.
$protected = get_post_meta( $request['id'], '_is_protected_content', true );
// If this is a protected page and the user is not logged in,
// don't allow them to access it.
// If desired, you could go a step further and check if they
// have a certain role/capabilities.
if ( $protected && ! is_user_logged_in() ) {
return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to view posts in this post type.' ), array( 'status' => rest_authorization_required_code() ) );
}
$post = $this->get_post( $request['id'] );
if ( is_wp_error( $post ) ) {
return $post;
}
if ( 'edit' === $request['context'] && $post && ! $this->check_update_permission( $post ) ) {
return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => rest_authorization_required_code() ) );
}
if ( $post && ! empty( $request['password'] ) ) {
// Check post password, and return error if invalid.
if ( ! hash_equals( $post->post_password, $request['password'] ) ) {
return new WP_Error( 'rest_post_incorrect_password', __( 'Incorrect post password.' ), array( 'status' => 403 ) );
}
}
// Allow access to all password protected posts if the context is edit.
if ( 'edit' === $request['context'] ) {
add_filter( 'post_password_required', '__return_false' );
}
if ( $post ) {
return $this->check_read_permission( $post );
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment