WP_REST_Posts_Controller::check_read_permission PHP Method

check_read_permission() public method

Correctly handles posts with the inherit status.
Since: 4.7.0
public check_read_permission ( object $post ) : boolean
$post object Post object.
return boolean Whether the post can be read.
    public function check_read_permission($post)
    {
        $post_type = get_post_type_object($post->post_type);
        if (!$this->check_is_post_type_allowed($post_type)) {
            return false;
        }
        // Is the post readable?
        if ('publish' === $post->post_status || current_user_can($post_type->cap->read_post, $post->ID)) {
            return true;
        }
        $post_status_obj = get_post_status_object($post->post_status);
        if ($post_status_obj && $post_status_obj->public) {
            return true;
        }
        // Can we read the parent if we're inheriting?
        if ('inherit' === $post->post_status && $post->post_parent > 0) {
            $parent = get_post($post->post_parent);
            return $this->check_read_permission($parent);
        }
        /*
         * If there isn't a parent, but the status is set to inherit, assume
         * it's published (as per get_post_status()).
         */
        if ('inherit' === $post->post_status) {
            return true;
        }
        return false;
    }

Usage Example

 /**
  * Check if a given request has access to delete meta for a post.
  *
  * @param  WP_REST_Request $request Full details about the request.
  * @return WP_Error|boolean
  */
 public function delete_item_permissions_check($request)
 {
     $parent = get_post((int) $request['parent_id']);
     if (empty($parent) || empty($parent->ID)) {
         return new WP_Error('rest_post_invalid_id', __('Invalid post id.'), array('status' => 404));
     }
     if (!$this->parent_controller->check_read_permission($parent)) {
         return new WP_Error('rest_forbidden', __('Sorry, you cannot view this post.'), array('status' => rest_authorization_required_code()));
     }
     $post_type = get_post_type_object($parent->post_type);
     if (!current_user_can($post_type->cap->delete_post, $parent->ID)) {
         return new WP_Error('rest_forbidden', __('Sorry, you cannot delete the meta for this post.'), array('status' => rest_authorization_required_code()));
     }
     return true;
 }
All Usage Examples Of WP_REST_Posts_Controller::check_read_permission