2016-11-21 111 views
0

我有一個應用程序,我試圖訪問需要登錄的安全Wordpress網頁。我發現Wordpress codex上的一些代碼,我認爲會強制登錄,但它似乎沒有做任何事情。我希望從用戶不存在的角度來說,我可以強制登錄。強制登錄Wordpress網站

function custom_login() { 
    $creds = array(); 
    $creds['user_login'] = 'myusername'; 
    $creds['user_password'] = 'mypassword'; 
    $creds['remember'] = true; 
    $user = wp_signon($creds, false); 
    if (is_wp_error($user)) 
     echo $user->get_error_message(); 
} 

function download_page() 
     { 
      global $wpdb; 
      $user = wp_get_current_user(); 

      if (!($user->exists())) { 

      custom_login(); 

      }else{ 
       return '<p>You\'re not logged in! <br /> <a style="color:#ffa200;" href="'. get_page_link(39) . '">Click here </a>' . 
       'to login and download products that you\'ve purchased.'; 
      } 
} 

回答

0

請嘗試以下代碼。寫入你的functions.php

function custom_login() { 
    $creds = array(); 
    $creds['user_login'] = 'myusername'; 
    $creds['user_password'] = 'mypassword'; 
    $creds['remember'] = true; 
    $user = wp_signon($creds, false); 
    if (!is_wp_error($user)) {  
     wp_clear_auth_cookie(); 
     wp_set_current_user ($user->ID); 
     wp_set_auth_cookie ($user->ID); 

     if($user->ID == 0) { 
      echo 'faild login'; 
     } else { 
      echo 'success'; 

     } 


    } else { 

        echo "The username and password you entered don't match."; 

    } 
     die(); 
    } 
add_action('wp_login', 'custom_login');