如何在wordpress中加载前端的wp-login.php?

时间:2016-05-14 14:59:51

标签: ajax wordpress wordpress-plugin

如果点击登录按钮并且我不想使用wp_login_form(),我想在我的网站首页上加载此登录页面,如下所示,因为我想要加载插件加载到wp-login.php页面的社交登录图标。

我知道可以使用Ajax完成,但由于我对语言不熟悉,我无法实现它。有关WordPress如何加载wp-login.php页面的任何帮助,如下图所示?

enter image description here

1 个答案:

答案 0 :(得分:1)

这不是一件容易的事,你是对的,你需要使用AJAX。

我将首先在其中添加文件和代码,然后尝试解释。

header.php

这显然可能与您有所不同,但您需要查看结构。如果需要,您可以删除注册部分。

<header id="main_header" class="clearfix">
    <div class="top_bar">
        <div class="container">
            <div class="ajax_login">
                <form id="login" action="login" method="post">
                    <h1><?php esc_attr_e('User login','yourtheme') ?></h1>
                    <p class="status"></p>
                    <input id="username" type="text" name="username" placeholder="<?php esc_attr_e('Username','yourtheme') ?>">
                    <input id="password" type="password" name="password" placeholder="<?php esc_attr_e('Password','yourtheme') ?>">
                    <div class="forgotten_box">
                        <a class="lost" href="<?php echo esc_url(wp_lostpassword_url()); ?>"><?php esc_attr_e('Lost your password?','yourtheme') ?></a>
                    </div>
                    <input class="submit_button" type="submit" value="Login" name="submit">
                    <?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
                </form>
                <div class="ajax_login_overlay"></div>
                <?php if (is_user_logged_in()):?>
                    <a class="login_button" href="<?php echo wp_logout_url( home_url() ); ?>"><?php esc_attr_e('Logout','yourtheme') ?></a>
                <?php else: ?>
                    <a class="login_button" id="show_login" href=""><?php esc_attr_e('Login','yourtheme') ?></a>
                <?php endif; ?>
            </div>
            <?php if (!is_user_logged_in()):?>
            <div class="register">
                <a class="lost" href="<?php echo esc_url(wp_registration_url()); ?>" id="show_register"><?php esc_attr_e('Register','yourtheme') ?></a>
                <form method="post" name="st-register-form" id="register_form">
                    <h2 class="register-heading"><?php esc_html_e( 'Register', 'yourtheme' ); ?></h2>
                    <div id="registration-error-message">
                    </div>
                    <div class="field">
                        <input type="text" autocomplete="off" name="username" id="yourtheme_register-username" placeholder="<?php esc_html_e( 'Username', 'yourtheme' ); ?>" />
                    </div>
                    <div class="field">
                        <input type="text" autocomplete="off" name="mail" id="yourtheme_register-email" placeholder="<?php esc_html_e( 'Email', 'yourtheme' ); ?>" />
                    </div>
                    <div class="field">
                        <input type="text" autocomplete="off" name="fname" id="yourtheme_register-fname" placeholder="<?php esc_html_e( 'First Name', 'yourtheme' ); ?>" />
                    </div>
                    <div class="field">
                        <input type="text" autocomplete="off" name="lname" id="yourtheme_register-lname" placeholder="<?php esc_html_e( 'Last Name', 'yourtheme' ); ?>" />
                    </div>
                    <div class="frm-button">
                        <input type="button" id="register-me" value="Register" />
                    </div>
                </form>
            </div>
            <?php endif; ?>
        </div>
    </div>
</header>

基本上是您使用AJAX提交的表单。没什么特别的。

顺其自然(未完成,你会想把它变成适合你的东西)

/*------------------------ AJAX login -------------------------*/
.top_bar{
    text-align: right;
}

.top_bar .ajax_login{
    display: inline-block;
    margin-right: 10px;
}

.top_bar .ajax_login_overlay{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgb(0,0,0);
    background: rgba(0,0,0,0.5);
    display: none;
    cursor: default;
    z-index: 101;
    transform: translateZ(1px);
}

.top_bar .ajax_login form#login{
    display: none;
    background-color: #FFFFFF;
    position: fixed;
    top: 50%;
    margin-top: -117px;
    z-index: 999;
    left: 50%;
    margin-left: -200px;
    cursor: default;
}

.top_bar .ajax_login form#login h1{
    color: #656565;
    background: #eee;
    font-weight: 700;
    text-transform: uppercase;
    font-size: 15px;
    padding: 2px 20px;
    text-align: left;
}

.top_bar .ajax_login form#login p.status{
    display: none;
    padding: 0 20px;
    margin-bottom: 12px;
}

.top_bar .ajax_login form#login input#username,
.top_bar .ajax_login form#login input#password{
    margin: 10px 20px;
    width: 400px;
    display: block;
}

.top_bar .ajax_login form#login .forgotten_box{
    display: inline-block;
    padding: 3px 20px 0 20px;
}

.top_bar .ajax_login form#login .forgotten_box .lost{
    display: block;
    padding: 5px;
    padding-left: 0;
    margin-bottom: 0;
}

.top_bar .ajax_login form#login input.submit_button{
    padding: 15px;
    border-radius: 4px;
    font-weight: 700;
    text-transform: uppercase;
    margin-right: 20px;
    float: right;
    cursor: pointer;
    -webkit-transition: all 180ms ease-in;
    -moz-transition: all 180ms ease-in;
    -o-transition: all 180ms ease-in;
    transition: all 180ms ease-in;
}

.top_bar .ajax_login .login_overlay{
    height: 100%;
    width: 100%;
    background-color: #F6F6F6;
    opacity: 0.9;
    position: fixed;
    z-index: 998;
}

.top_bar .ajax_login .login_button,
.top_bar .register a{
    display: inline-block;
    color:  #0c0f0b;
    font-size: 12px;
    font-weight: 700;
    line-height: 30px;
}

.top_bar .ajax_login .login_button:hover{
    color: #d84949;
}

.top_bar .register{
    display: inline-block;
}

/*------------------------ AJAX register -------------------------*/
.top_bar .register #register_form{
    display: none;
    background-color: #FFFFFF;
    position: fixed;
    top: 50%;
    margin-top: -117px;
    z-index: 999;
    left: 50%;
    margin-left: -200px;
    cursor: default;
}

.top_bar .register #register_form input[type="text"]{
    margin: 10px 20px;
    width: 400px;
    display: block;
    background: #f2f2f2;
    border: 0;
    font-family: 'Roboto', sans-serif;
    color: rgb(115, 115, 115);
    color: rgba(115, 115, 115, 0.5);
    font-size: 14px;
    font-weight: 400;
    line-height: 20px;
    text-align: left;
    font-style: italic;
}

.top_bar .register #register_form .register-heading{
    background: #be0017;
    font-family: Arial;
    color:  #ffffff;
    font-size: 16px;
    line-height: 12px;
    font-weight: 700;
    letter-spacing: 0.64px;
    text-align: left;
    padding:15px 20px;
    text-transform:uppercase;
}

<强>的functions.php

您可以在functions.php或您functions.php文件中包含的单独文件中添加此内容。这是AJAX回调函数,admin-ajax.php等的本地化。

<?php
/********* AJAX Login ***********/
function yourtheme_ajax_login_init(){
    wp_register_script('ajax-login-script', get_template_directory_uri() . '/js/ajax-login-script.js', array('jquery') );
    wp_enqueue_script('ajax-login-script');
    wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'redirecturl' => home_url(),
        'loadingmessage' => esc_html__('Sending user info, please wait...', 'yourtheme')
    ));
    // Enable the user with no privileges to run ajax_login() in AJAX
    add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
    add_action('init', 'yourtheme_ajax_login_init');
}
if (!function_exists('ajax_login')) {
    function ajax_login(){
        // First check the nonce, if it fails the function will break
        check_ajax_referer( 'ajax-login-nonce', 'security' );
        // Nonce is checked, get the POST data and sign user on
        $info = array();
        $info['user_login'] = $_POST['username'];
        $info['user_password'] = $_POST['password'];
        $info['remember'] = true;
        $user_signon = wp_signon( $info, false );
        if ( is_wp_error($user_signon) ){
            echo json_encode(array('loggedin'=>false, 'message'=> esc_html__('Wrong username or password.', 'yourtheme')));
        } else {
            echo json_encode(array('loggedin'=>true, 'message'=> esc_html__('Login successful, redirecting...', 'yourtheme')));
        }
        die();
    }
}
/********* AJAX Registration ***********/
add_action( 'wp_ajax_register_action', 'yourtheme_handle_registration' );
add_action( 'wp_ajax_nopriv_register_action', 'yourtheme_handle_registration' );
if (!function_exists('yourtheme_handle_registration')) {
    function yourtheme_handle_registration(){
        if( $_POST['action'] == 'register_action' ) {
            $error = '';
            $uname = trim( $_POST['username'] );
            $email = trim( $_POST['mail_id'] );
            $fname = trim( $_POST['firname'] );
            $lname = trim( $_POST['lasname'] );
            if( empty( $_POST['username'] ) )
                $error .= '<p class="error">'.esc_html__('Enter username', 'yourtheme').'</p>';
            if( empty( $_POST['mail_id'] ) )
                $error .= '<p class="error">'.esc_html_('Enter email', 'yourtheme').'</p>';
            elseif( !filter_var($email, FILTER_VALIDATE_EMAIL) )
                $error .= '<p class="error">'.esc_html__('Enter valid email', 'yourtheme').'</p>';
            if( empty( $_POST['firname'] ) )
                $error .= '<p class="error">'.esc_html__('Enter first name', 'yourtheme').'</p>';
            elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) )
                $error .= '<p class="error">'.esc_html__('Enter valid first name', 'yourtheme').'</p>';
            if( empty( $_POST['lasname'] ) )
                $error .= '<p class="error">'.esc_html__('Enter last name', 'yourtheme').'</p>';
            elseif( !preg_match("/^[a-zA-Z'-]+$/",$lname) )
                $error .= '<p class="error">'.esc_html__('Enter valid last name', 'yourtheme').'</p>';
            if( empty( $error ) ){
                $status = wp_create_user( $uname, $email );
                if( is_wp_error($status) ){
                    $msg = '';
                    foreach( $status->errors as $key=>$val ){
                        foreach( $val as $k=>$v ){
                            $msg = '<p class="error">'.$v.'</p>';
                        }
                    }
                    echo $msg;
                } else{
                    $msg = '<p class="success">'.esc_html__('Registration successful!', 'yourtheme').'</p>';
                    echo $msg;
                }
            } else{
                echo $error;
            }
            die(1);
        }
    }
}
add_action( 'user_register', 'yourtheme_register_user_metadata' );
add_action( 'profile_update', 'yourtheme_register_user_metadata' );
if (!function_exists('yourtheme_register_user_metadata')) {
    function yourtheme_register_user_metadata( $user_id ){
        if( !empty( $_POST['firname'] ) && !empty( $_POST['lasname'] ) && !empty( $_POST['username'] ) && !empty( $_POST['mail_id'] ) ){
            update_user_meta( $user_id, 'first_name', trim($_POST['firname']) );
            update_user_meta( $user_id, 'last_name', trim($_POST['lasname']) );
            update_user_meta( $user_id, 'username', trim($_POST['username']) );
            update_user_meta( $user_id, 'mail_id', trim($_POST['mail_id']) );
        }
        update_user_meta( $user_id, 'show_admin_bar_front', false );
    }
}

<强> AJAX登录-的script.js

实际的AJAX调用以及点击时显示和隐藏登录框。

jQuery(document).ready(function($) {
    "use strict";

    // Show the login dialog box on click
    $('a#show_login').on('click', function(e){
        $('.ajax_login_overlay').fadeIn(500);
        $('form#login').fadeIn(500);
        e.preventDefault();
    });

    $('.ajax_login_overlay').on('click', function(e){
        $('form#login').fadeOut(500);
        $('.ajax_login_overlay').fadeOut(500);
        $('form#register_form').hide();
        $('.ajax_login .status').html('');
        $('#registration-error-message').html('');
        $('form#login').hide();
        $('form#register_form .field input').val('');
    });

    // Perform AJAX login on form submit
    $('form#login').on('submit', function(e){
        $('form#login p.status').show().text(ajax_login_object.loadingmessage);
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajax_login_object.ajaxurl,
            data: {
                'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
                'username': $('form#login #username').val(),
                'password': $('form#login #password').val(),
                'security': $('form#login #security').val() },
            success: function(data){
                $('form#login p.status').text(data.message);
                if (data.loggedin === true){
                    document.location.href = ajax_login_object.redirecturl;
                }
            }
        });
        e.preventDefault();
    });

    //Register

    $('a#show_register').on('click', function(e){
        $('.ajax_login_overlay').fadeIn(500);
        $('form#register_form').fadeIn(500);
        e.preventDefault();
    });

    $(document).on('click', '#register-me', function(){

        var action   = 'register_action';
        var username = $("#yourtheme_register-username").val();
        var mail_id  = $("#yourtheme_register-email").val();
        var firname  = $("#yourtheme_register-fname").val();
        var lasname  = $("#yourtheme_register-lname").val();

        var ajaxdata = {
            action: 'register_action',
            username: username,
            mail_id: mail_id,
            firname: firname,
            lasname: lasname,
        };

        $.post( ajax_login_object.ajaxurl, ajaxdata, function(res){
            $("#registration-error-message").html(res);
        });

    });

});

enter image description here

enter image description here

现在,我对此进行了测试,但它确实有效,但是当您创建用户并登录(清理等)时,它需要更多的测试/验证检查,尤其是安全性。这不是我的代码的100%,我发现它在线上,并将其混合成一个。仍然需要改进imo。

希望这有帮助,我计划在找到时间之后写一篇关于此的完整教程:)