title: Wordpress - Fatal error: Call to a member function get_var() on a non-object $wpdb
body: <p><a href="https://wordpress.stackexchange.com/questions/91848/storing-password-functions-php">[Solution by s_ha_dum on http://wordpress.stackexchange.com]</a></p>
  
  <p>I'm trying to direct users to a certain post based on a password entered in post settings. I have almost working code:</p>
  
  <p>Form on page:</p>
  
  <pre><code>&lt;form method="post" action=""&gt;
    &lt;input type="password" name="passwordfield"&gt;
    &lt;input type="hidden" name="homepagepassword" value="1"&gt;
    &lt;input type="submit" value="Submit"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Code in functions.php</p>
  
  <pre><code>function doPasswordStuff(){
      if(isset($_POST['homepagepassword'])){
      $post_password = $_POST['passwordfield'];
      $post_id = $wpdb-&gt;get_var( $wpdb-&gt;prepare("SELECT ID FROM $wpdb-&gt;posts WHERE post_password = %s", $post_password) );
      $q = new WP_Query( 'p=$post_id' );
      if($q-&gt;have_posts()){
          while($q-&gt;have_posts()){
              $q-&gt;the_post();
              wp_redirect(get_permalink());
              die();
          }
      } else {
          // oh dear, there isnt a post with this 'password', put a redirect to a fallback here
          wp_redirect('http://www.google.com');
          die();
      }
      wp_reset_query();
      }
  }
  add_action('init','doPasswordStuff');
  </code></pre>
  
  <p>However I'm getting fatal error (Fatal error: Call to a member function get_var() on a non-object) on this line: </p>
  
  <blockquote>
    <p>$post_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts
    WHERE post_password = %d", $post_password) );</p>
  </blockquote>
  
  <p>If would really appreciate if someone would take a look :) thanks!</p>