title: Wordpress - How to login user to frontend programmatically
body: <p>I created function for loging in users on frontend using this example: <a href="https://gist.github.com/iandunn/8162246" rel="nofollow">https://gist.github.com/iandunn/8162246</a></p>
  
  <p>After user logs in <code>is_user_logged_in()</code> function returns <code>true</code> only inside this function where I placed code for login part.</p>
  
  <p>How do I login users globally?
  This is my code:</p>
  
  <pre><code>function programmatic_login( $username ) {
      if ( is_user_logged_in() ) {
          wp_logout();
      }
      add_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );
      $user = wp_signon( array( 'user_login' =&gt; $username ) );
      remove_filter( 'authenticate', 'allow_programmatic_login', 10, 3 );
      if ( is_a( $user, 'WP_User' ) ) {
          $user_id = $user-&gt;ID;
  
          if( $user ) {
              wp_set_current_user( $user_id, $user-&gt;user_login );
              wp_set_auth_cookie( $user_id );
              do_action( 'wp_login', $user-&gt;user_login );
          }
          if ( is_user_logged_in() ) {
              return true;
          }
      }
  
      return false;
  }
  
  function allow_programmatic_login( $user, $username, $password ) {
      return get_user_by( 'login', $username );
  }
  
  function process_login(){
  
      // this comes from login form
      $username = $_POST["login_username"];
  
      programmatic_login( $username );
  
      // it returns true only here, on any other function it returns false
      if(is_user_logged_in()){
          echo "ok";
      }else{
          echo "not ok";
      }
  
  }
  </code></pre>
  
  <p>This is one example where I try to check if user is logged in, outside previous function:</p>
  
  <pre><code>add_filter('wp_nav_menu_items', 'add_login_logout_link', 10, 2);
  
  function add_login_logout_link($items, $args) {
  
      $loginPage = get_page_by_title("Login");
      $registerPage = get_page_by_title("Register");
  
      if(is_user_logged_in()){
          $items .= "&lt;li&gt;&lt;a href='" . wp_logout_url('index.php') . "' title='Logout'&gt;Logout&lt;/a&gt;&lt;/li&gt;";
      }else{
          $items .= "&lt;li&gt;&lt;a href='". site_url() . '/' . '?page_id=' . $loginPage-&gt;ID ."'&gt;Login&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a a href='". site_url() . '/' . '?page_id=' . $registerPage-&gt;ID ."'&gt;Register&lt;/a&gt;&lt;/li&gt;";
      }
  
      return $items;
  }
  </code></pre>