Hun*_*ght 3 php wordpress wordpress-plugin
[s_ha_dum在http://wordpress.stackexchange.com上的解决方案]
我正在尝试根据在帖子设置中输入的密码将用户定向到某个帖子.我有几乎工作的代码:
页面上的表格:
<form method="post" action="">
<input type="password" name="passwordfield">
<input type="hidden" name="homepagepassword" value="1">
<input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)
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');
Run Code Online (Sandbox Code Playgroud)
但是我在这一行上遇到致命错误(致命错误:在非对象上调用成员函数get_var()):
$ post_id = $ wpdb-> get_var($ wpdb-> prepare("SELECT ID FROM $ wpdb-> posts WHERE post_password =%d",$ post_password));
如果有人愿意看看我真的很感激:)谢谢!
Luc*_*oni 10
在此之前全局化$ wpdb
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' );
最佳做法是使用小写表/列名称
然后像这样重定向
<?php if ( $q->have_posts() ) : while ( $q->have_posts() ) : $q->the_post(); ?>
wp_redirect( the_permalink() );
<?php endif;?>
还使用http状态代码作为wp_redirect()的第二个参数.这可能对HTTP STATUS CODES有帮助