[Solution by s_ha_dum on http://wordpress.stackexchange.com]
I'm trying to direct users to a certain post based on a password entered in post settings. I have almost working code:
Form on page:
<form method="post" action="">
<input type="password" name="passwordfield">
<input type="hidden" name="homepagepassword" value="1">
<input type="submit" value="Submit">
</form>
Code in functions.php
function doPasswordStuff(){
if(isset($_POST['homepagepassword'])){
$post_password = $_POST['passwordfield'];
$post_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_password = %s", $post_password) );
$q = new WP_Query( 'p=$post_id' );
if($q->have_posts()){
while($q->have_posts()){
$q->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');
However I'm getting fatal error (Fatal error: Call to a member function get_var() on a non-object) on this line:
$post_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_password = %d", $post_password) );
If would really appreciate if someone would take a look :) thanks!
globalize $wpdb before this
global $wpdb
$post_id = $wpdb->get_var( $wpdb->prepare("SELECT id FROM $wpdb->posts WHERE post_password = %s", $post_password) ); $q = new WP_Query( 'p=$post_id' );
Also it is a best practise to use lowercase table/column names
and then redirect like so
<?php if ( $q->have_posts() ) : while ( $q->have_posts() ) : $q->the_post(); ?>
wp_redirect( the_permalink() );
<?php endif;?>
Also use a http status code as the second parameter to wp_redirect() This might be helpful HTTP STATUS CODES