Limit REST API output to current logged in user that is also author of the content

https://developer.wordpress.org/rest-api/using-the-rest-api/frequently-asked-questions/#require-authentication-for-all-requests
This requires authentication for all reque​sts.

add_filter( 'rest_authentication_errors', function( $result ) {
    if ( ! empty( $result ) ) {
        return $result;
    }
    if ( ! is_user_logged_in() ) {
        return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', array( 'status' => 401 ) );
    }
    return $result;
});

Now when I add a is_user_logged_in condition to this then I only see the content where the current logged in user is also the author. This is exactly what I am after.

However I am not sure if just returning a simple string of text inside the condition is the right way to do this. I mean why is this happening at all? Why is the REST API limiting the content shown when I return any string of text inside that condition? This is what I would like to know more about.

add_filter('rest_authentication_errors', function ($result) {
    if (!empty($result)) {
        return $result;
    }
    if (!is_user_logged_in()) {
        return new WP_Error('rest_not_logged_in', 'You are not currently logged in.', array('status' => 401));
    }
    // if I add this condition only the content per user that is also author is shown in REST API
    // why is that so?
    if (is_user_logged_in()) {
        // what else could I put here to limit the content to current logged in user that is also author?
        // this kind of looks bad, what is the right way to do this?
        return 'Show only the content that the current logged in user created';
    }
    return $result;
});

0

Leave a Comment