Using WordPress ‘rest_cookie_collect_status()’ PHP function

The rest_cookie_collect_status WordPress PHP function collects cookie authentication status.

Usage

$status = rest_cookie_collect_status();

Parameters

  • None

More information

See WordPress Developer Resources: rest_cookie_collect_status

Examples

Collect authentication status

Collect the current authentication status and store it in a variable.

$status = rest_cookie_collect_status(); // Collects authentication status

Check if user is authenticated

Check if the user is authenticated by examining the status object.

$status = rest_cookie_collect_status();
$is_authenticated = empty($status); // True if authenticated, false otherwise

Display an error message for non-authenticated users

Display an error message to non-authenticated users.

$status = rest_cookie_collect_status();
if (!empty($status)) {
    echo "You are not authenticated."; // Display error message
}

Display authentication status

Display the authentication status and its details.

$status = rest_cookie_collect_status();
if (empty($status)) {
    echo "You are authenticated.";
} else {
    echo "You are not authenticated. Status details: " . print_r($status, true);
}

Use the authentication status with REST API endpoints

Check the authentication status before processing a REST API request.

add_filter('rest_pre_dispatch', 'check_auth_status', 10, 3);
function check_auth_status($result, $server, $request) {
    $status = rest_cookie_collect_status();
    if (!empty($status)) {
        return new WP_Error('rest_forbidden', 'You are not authenticated.', array('status' => 403));
    }
    return $result;
}