1

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?

  • The 'read' capability requires authentication, and is for allowing access to the WordPress dashboard and the user's profile page - see this. – Sally CJ Dec 8 '18 at 13:16
  • 1
    @SallyCJ The first paragraph from the linked resource says "to control what users can and cannot do" - this implies roles and capabilities have nothing to do with guests (and hence current_user_can() always returns false for a guest). Am I wrong? – kero Dec 8 '18 at 13:22
  • For standard Posts (post post type), the current_user_can($pto->cap->read) in the code is equivalent to current_user_can( 'read' ); so looking at what the 'read' capability is for, I think it's normal for guests to have no 'read' capability despite they can of course freely do things like read posts, post comments, etc. that don't need capabilities which require authentication or special cookie/session. That's what I was trying to say @kero. But do correct me if I'm wrong. – Sally CJ Dec 8 '18 at 14:30
  • 1
    Hi @SallyCJ, thanks for the clarifiction on "read" capability. I have removed that from the example code to avoid confusion. – Lucas Bustamante Dec 8 '18 at 14:33
  • 1
    I don't have the time now to dig deeper, but as I see it right now the answer would be: guests have no capabilities. Also it seems, capabilities are used most of the time in the backend (and since guests can't access the backend, they don't need capabilities) – kero Dec 8 '18 at 14:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.