In WordPress, a guest can do a lot of things, such as reading posts.
However, this always returns false for guests:
add_action('wp', function() {
global $post;
/** @var WP_Post_Type $pto */
$pto = get_post_type_object(get_post_type($post->ID));
/** @var bool $cap */
$cap = current_user_can($pto->cap->read_post);
});
I see that current_user_can()
triggers this piece of code for guests:
// wp-includes/user.php @ line 2613 (WordPress 5.0.0)
wp_set_current_user( 0 );
return $current_user;
Thus running assertions on this WP_User
object:
WP_User Object
(
[data] => stdClass Object
(
)
[ID] => 0
[caps] => Array
(
)
[cap_key] =>
[roles] => Array
(
)
[allcaps] => Array
(
)
[filter] =>
[site_id:WP_User:private] => 0
)
Which means it has no capability at all, probably why it's failing.
Given that a guest can actually read a post, why this returns false?
Being such assertions critical for security, how can I assert if a guest is allowed to do something in WordPress, such as reading a post type, or a post ID?