2

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;
});
  • What endpoint have you tried? Can you re-explain what are you really trying to do? There are various endpoints, you know. And you shouldn't return the string there.. because for example with the wp/v2/posts endpoint, all logged-in users would be able to see private posts which by default requires authentication. – Sally CJ Oct 18 at 14:46

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.