数据库新手黑客在这里。我通过编码一个WP模板文件来烦恼,该模板文件从另一个站点的WP DB检索帖子数据。它正常工作了大约2年,突然停止工作-崩溃了,页面无法完成加载。出现“ 该网站遇到技术困难。”错误。
我注释了:: prepare方法来尝试找出问题,并且页面已完成加载,但仍然没有帖子中的数据...这里还是新手,所以我确定经验丰富的兽医可能会看到此问题。感谢您提供任何见识!
<?php
$originaldb = new wpdb('XXXXXX','XXXXXX','XXXXXX','XXXXXXXX');
//Home Recent POST
$post_id_recent = get_field('recent_post_id');
$prep_recent = $originaldb->prepare("SELECT * FROM wp_posts WHERE $wpdb->posts.ID = $post_id_recent");
$recent = $originaldb->get_results($prep_recent);
$prep_recent_thumb = $originaldb->prepare("
SELECT p1.*, wm2.meta_value FROM wp_posts p1 LEFT JOIN
wp_postmeta wm1 ON (
wm1.post_id = $post_id_recent
AND wm1.meta_value IS NOT NULL
AND wm1.meta_key = '_thumbnail_id'
)
LEFT JOIN wp_postmeta wm2 ON (wm1.meta_value = wm2.post_id AND wm2.meta_key = '_wp_attached_file'
AND wm2.meta_value IS NOT NULL) WHERE p1.post_status='publish' AND p1.post_type='post'
");
$recent_thumb = $originaldb->get_results($prep_recent_thumb);
foreach ($recent_thumb as $obj) :
$url = $obj->meta_value;
endforeach; ?>
<?php foreach ($recent as $obj) : ?>
<div class="home_recent_thumb" style="background-image:url(<?php echo 'http://kuteblackson.com/blog/wp-content/uploads/'.$url; ?>)" onclick="location.href='<?php echo $obj->guid; ?>';"></div>
<div class="home_recent_content">
<div class="home_recent_title"><a href="<?php echo $obj->guid; ?>"><?php echo $obj->post_title; ?></a></div>
<div class="home_recent_excerpt"><?php echo $obj->post_excerpt; ?></div>
<a href="<?php echo $obj->guid; ?>" class="button medium radius home_blog_button">READ BLOG</a><br>
<a href="blog" style="font-size: 16px; color: #9e9898; text-decoration:underline;">See all blog posts</a>
</div><!-- end .home_recent_content -->
<div style="clear:both;"></div>
<?php endforeach; wp_reset_query(); ?>
答案 0 :(得分:0)
您没有正确使用prepare()方法。
从文档中:
参数
$ query (字符串)(必需)具有类似sprintf()占位符的查询语句
$ args (数组|混合)(必需)(如果用参数数组调用,则替换为查询的占位符的变量数组;如果使用参数数组,则替换为查询的占位符的第一个变量)被单独的论点调用。
$ args,... (混合)(必需)(如果有单独的参数被调用),其他变量将替换为查询的占位符。
在您的代码中,对prepare()
方法的两个调用都仅传递第一个参数(查询),并且该方法期望至少有两个参数,这就是代码触发错误的原因,因此您得到了“该站点遇到技术困难”消息。
您的prepare()
通话应如下所示:
$prep_recent = $originaldb->prepare(
"SELECT * FROM wp_posts WHERE $wpdb->posts.ID = %d",
array($post_id_recent)
);
$prep_recent_thumb = $originaldb->prepare("
SELECT p1.*, wm2.meta_value FROM wp_posts p1 LEFT JOIN
wp_postmeta wm1 ON (
wm1.post_id = %d
AND wm1.meta_value IS NOT NULL
AND wm1.meta_key = '_thumbnail_id'
)
LEFT JOIN wp_postmeta wm2 ON (
wm1.meta_value = wm2.post_id
AND wm2.meta_key = '_wp_attached_file'
AND wm2.meta_value IS NOT NULL
)
WHERE p1.post_status='publish' AND p1.post_type='post'",
array($post_id_recent)
);
请注意,在两种情况下,$post_id_recent
变量都作为第二个参数传递给prepare()
方法。这应该可以解决问题(假设这是唯一的问题。)