0
X
Add Snippet To Project
New Project
Add To Existing Project
<?php
<?php
namespace WPTurbo;
add_action( 'init', 'wpturbo_custom_login' );
function wpturbo_custom_login() {
// Check if user is trying to log in
if ( isset( $_POST['log'] ) && isset( $_POST['pwd'] ) && isset( $_POST['_wpnonce'] ) && wp_verify_nonce( $_POST['_wpnonce'], 'wpturbo_login_action' ) ) {
$username = sanitize_user( $_POST['log'] );
$password = $_POST['pwd'];
$creds = [
'user_login' => $username,
'user_password' => $password,
'remember' => true,
];
$user = wp_signon( $creds, false );
if ( ! is_wp_error( $user ) ) {
wp_redirect( admin_url() ); // Redirect to admin area
exit;
} else {
echo '<p class="error">' . esc_html( $user->get_error_message() ) . '</p>';
}
}
// Display the login form
if ( ! is_user_logged_in() ) {
echo '<form method="post" action="' . esc_url( $_SERVER['REQUEST_URI'] ) . '">';
echo '<label for="log">Username:</label>';
echo '<input type="text" name="log" id="log" required />';
echo '<label for="pwd">Password:</label>';
echo '<input type="password" name="pwd" id="pwd" required />';
// Adding a nonce field for security
wp_nonce_field( 'wpturbo_login_action', '_wpnonce' );
echo '<input type="submit" value="Login" />';
echo '</form>';
}
}
These changes aim to enhance the security of your custom login functionality by verifying legitimate requests and reducing the potential for malicious actions. Always review and test your code thoroughly to ensure its security and functionality.