Почему моя форма входа в Wordpress застревает в перенаправлении l oop? - PullRequest
0 голосов
/ 20 апреля 2020

В настоящее время я создаю приложение Wordpress, для которого требуется пользовательская форма входа в систему, которая затем перенаправляет пользователя на страницу панели мониторинга после входа в систему.

Однако форма входа в систему застревает в перенаправлении. l oop, и иногда просто обновляет страницу входа при отправке, вместо перенаправления пользователя.

Любые мысли о том, почему это происходит, очень приветствуются

// login. php

<form id="login" action="login" method="post" class="row">

            <div class="col-md-12 mb-3">
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text" id="inputGroupPrepend">@</span>
                </div>
                <input type="text" class="form-control" id="username" placeholder="Username" name="username" aria-describedby="inputGroupPrepend" required>
              </div>
            </div>

            <div class="col-md-12 mb-3">
              <div class="input-group">
                <div class="input-group-prepend">
                  <span class="input-group-text" id="inputGroupPrepend">
                    <svg class="bi bi-lock-fill" width="1em" height="1em" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
                      <rect width="11" height="9" x="4.5" y="8" rx="2"/>
                      <path fill-rule="evenodd" d="M6.5 5a3.5 3.5 0 117 0v3h-1V5a2.5 2.5 0 00-5 0v3h-1V5z" clip-rule="evenodd"/>
                    </svg>
                  </span>
                </div>
                <input type="password" class="form-control "name="password" placeholder="Password" aria-describedby="inputGroupPrepend" id="password" />
              </div>
            </div>

            <div class="col-md-12 mb-3">
              <div class="input-group">
                <input type="submit" name="submit" value="Log in">
              </div>
            </div>

            <div class="col-md-12 mb-3">
              <p><a class="lost small" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a></p>
              <p class="status"></p>
            </div>

                <?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>

            </form>

// ajax -login.script. js

jQuery(document).ready(function() {

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

});

// функции. php

    function ajax_login_init(){

        wp_register_script('ajax-login-script', get_template_directory_uri() . '/app/js/ajax-login-script.js', array('jquery') );
        wp_enqueue_script('ajax-login-script');

        wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
            'ajaxurl' => home_url() . '/wp-admin/admin-ajax.php',
            'redirecturl' => get_permalink(200),
            'loadingmessage' => __('')
        ));

        // 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', 'ajax_login_init');
    }

    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'=>__('Wrong username or password.')));
        } else {
            echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
        }

            die();
    }

// logout redirect
add_action('wp_logout','ps_redirect_after_logout');
function ps_redirect_after_logout(){
   wp_redirect( get_permalink(9) );
   exit();
}

// destroy sessions on logout
function destroy_sessions() {
   $sessions->destroy_all();//destroys all sessions
   wp_clear_auth_cookie();//clears cookies regarding WP Auth
}
add_action('wp_logout', 'destroy_sessions');

// header. php

<?php

    // check user login success/fail and redirect to dashboard page
    if (is_user_logged_in() && is_page(9)) {
        wp_redirect( get_permalink( 200 ) );
        exit;
    }

?>

1 Ответ

0 голосов
/ 01 мая 2020

Интересно, я использую почти тот же код :). Вот что, я думаю, вы должны изменить:

1) admin_url, удалить / wp-admin / вам это не понадобится

2) home_url вместо get_permalink

3 ) удалить вашу add_action из вашей функции.

if ( ! function_exists( 'ajax_login_init' ) ) {
function ajax_login_init(){
wp_register_script('ajax-login-script', get_stylesheet_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('/my-account/'),
    'loadingmessage' => __('Sending user info, please wait...')
));

// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login_init' );
 }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...