问题描述
我正在尝试根据在帖子设置中输入的密码将用户定向到某个帖子.我几乎有工作代码:
I'm trying to direct users to a certain post based on a password entered in post settings. I have almost working code:
页面上的表单:
<form method="post" action="">
<input type="password" name="passwordfield">
<input type="hidden" name="homepagepassword" value="1">
<input type="submit" value="Submit">
</form>
functions.
Code in functions.
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');
但是我在这一行遇到了致命错误(致命错误:在非对象上调用成员函数 get_var()):
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->postsWHERE post_password = %d", $post_password) );
如果有人能看一下,真的会很感激:)谢谢!
If would really appreciate if someone would take a look :) thanks!
推荐答案
在此之前全局化 $wpdb
globalize $wpdb before this
全局 $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
然后像这样重定向
have_posts() ) : $q->the_post();?>
wp_redirect( the_permalink() );
还使用 http 状态代码作为 wp_redirect() 的第二个参数这可能会有所帮助HTTP 状态代码
Also use a http status code as the second parameter to wp_redirect()This might be helpfulHTTP STATUS CODES
这篇关于Wordpress - 致命错误:在非对象 $wpdb 上调用成员函数 get_var()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!