0
function custom_login_authentication($username, $password) {
    // Set API endpoint URL
    $url = "https://webapi.barecms.com/api/users/login";
    
    $data = array(
        'email' => $username,
        'password' => $password
    );
    
    $json_data = json_encode($data);

    // Initialize cURL session
    $ch = curl_init();

    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

    $response = curl_exec($ch);

    // Close cURL session
    curl_close($ch);

    // Handle the API response
    $response_data = json_decode($response, true);
    var_dump($response_data);
    var_dump($user);


    if ($response_data && isset($response_data['success']) && $response_data['success'] === 1) {
        // User login is successful, log them into WordPress
        $user = get_user_by('email', $username);
        
        if ($user) {
            wp_set_auth_cookie($user->ID, true);
            wp_set_current_user($user->ID, $username);
            do_action('wp_login', $username);
        }
    } else {
        // User login failed, handle the error
        $error_message = "Invalid username or password.";
        wp_redirect(wp_login_url() . '?login=failed&message=' . urlencode($error_message));
        exit;
    }
}
add_action('wp_authenticate', 'custom_login_authentication', 20, 2);

function custom_login_failed($username) {
    $referrer = wp_get_referer();

    // Redirect back to the login page with an error message
    wp_redirect(add_query_arg('login', 'failed', $referrer));
    exit;
}
add_action('wp_login_failed', 'custom_login_failed');
2
  • Welcome to WPSE! Please edit your question to let us know what specific problem you're having. What's the expected outcome? What's not working? Do you get any errors? Code-only questions aren't really questions.
    – Pat J
    May 26 at 14:01
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    44 mins ago

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.