gpt4 book ai didi

php - WordPress - fatal error : Call to a member function get_var() on a non-object $wpdb

转载 作者:可可西里 更新时间:2023-11-01 00:09:43 28 4
gpt4 key购买 nike

[Solution by s_ha_dum on 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>

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');

但是我在这一行遇到 fatal error ( fatal error :调用非对象上的成员函数 get_var()):

$post_id = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_password = %d", $post_password) );

如果有人愿意看一下,我将不胜感激 :) 谢谢!

最佳答案

在此之前全局化$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

关于php - WordPress - fatal error : Call to a member function get_var() on a non-object $wpdb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15548816/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com