WordPress.org

Make WordPress Core

Ticket #38276: poc-1.php

File poc-1.php, 1.8 KB (added by jdgrimes, 4 years ago)

Basic POC of what an API like this might look like

Line 
1<?php
2
3/**
4 * Check if something is accessible to the current user.
5 *
6 * Checks whether the current user is allowed to see this item.
7 *
8 * @since 4.7.0
9 *
10 * @param string $type The type of thing this is, e.g., 'post', 'term', etc.
11 * @param int    $id   The ID of the thing.
12 *
13 * @return bool Whether the thing is accessible to the current user.
14 */
15function is_thing_accessible( $type, $id ) {
16        return is_thing_accessible_for_user( get_current_user_id(), $type, $id );
17}
18
19/**
20 * Check if something is accessible to a particular user.
21 *
22 * Checks whether the user is allowed to see this item.
23 *
24 * @since 4.7.0
25 *
26 * @param int    $user_id The ID of the user, or 0 for non-logged-in users.
27 * @param string $type    The type of thing this is, e.g., 'post', 'term', etc.
28 * @param int    $id      The ID of the thing.
29 *
30 * @return bool Whether the thing is accessible to the user.
31 */
32function is_thing_accessible_for_user( $user_id, $type, $id ) {
33
34        // Everything is public by default, unless restricted by something.
35        $is_accessible = true;
36
37        switch ( $type ) {
38
39                case 'post':
40                        $post_status = get_post_status_object( get_post_status( $id ) );
41
42                        // If the post doesn't have a public status, fall back to the caps API.
43                        if ( ! $post_status || ! $post_status->public ) {
44                                $is_accessible = user_can( $user_id, 'read_post', $id );
45                        }
46                break;
47        }
48
49        /**
50         * Filter whether a thing is accessible to a user.
51         *
52         * @since 4.7.0
53         *
54         * @param bool   $is_accessible Whether the thing is accessible to this user.
55         * @param int    $user_id       The ID of the user, or 0 for non-logged-in users.
56         * @param string $type          The type of thing this is, e.g., 'post', 'term', etc.
57         * @param int    $id            The ID of the thing.
58         */
59        return apply_filters( 'is_thing_accessible', $is_accessible, $user_id, $type, $id );
60}