WPDB多个网站的帖子和获得特色图片

时间:2016-02-04 作者:RCNeil

我正在使用下面的代码查询5个Wordpress站点的帖子,将它们合并成一个数组,按日期对数组进行排序,然后显示它们:

//SITE 1
$mydb = new wpdb(\'xxxx\',\'xxxx\',\'xxxx\',\'localhost\');
if($mydb) { 
    $query1 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = \'post\' AND post_status = \'publish\'", OBJECT); 
}
$mydb->flush(); 

//SITE 2
$mydb = new wpdb(\'xxxx\',\'xxxx\',\'xxxx\',\'localhost\');
if($mydb) { 
    $query2 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = \'post\' AND post_status = \'publish\'", OBJECT); 
}
$mydb->flush(); 

//SITE 3
$mydb = new wpdb(\'xxxx\',\'xxxx\',\'xxxx\',\'localhost\');
if($mydb) { 
    $query3 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = \'post\' AND post_status = \'publish\'", OBJECT); 
}
$mydb->flush(); 

//SITE 4
$mydb = new wpdb(\'xxxx\',\'xxxx\',\'xxxx\',\'localhost\');
if($mydb) { 
    $query4 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = \'post\' AND post_status = \'publish\'", OBJECT); 
}
$mydb->flush(); 

//SITE 5
$mydb = new wpdb(\'xxxx\',\'xxxx\',\'xxxx\',\'localhost\');
if($mydb) { 
    $query5 = $mydb->get_results("SELECT * FROM wp_posts WHERE post_type = \'post\' AND post_status = \'publish\'", OBJECT); 
}
$mydb->flush(); 


//MERGE ARRAYS
$allsitearrays = array_merge($query1, $query2, $query3, $query4, $query5);


//SORT BY DATE
function cmp($a, $b) {
  if ($a->post_date == $b->post_date) {
    return 0;
  } else {
    return $a->post_date < $b->post_date ? 1 : -1; // reverse order
  }
}
usort($allsitearrays, \'cmp\');



//OUTPUT
if ( $allsitearrays ):
    global $post; 
    foreach($allsitearrays as $post) {

        //OUTPUT HERE

    }
endif;
这是伟大的工作,除了我无法检索该职位的特色图像与此方法。我不能使用本机函数,如wp_get_attachment_image_src, 我想在循环中再次查询DB,因为每个帖子都试图找到它的postmeta,这最终会太过火,并且有太多的查询。

有没有一种方法可以获取我在第一次查询中查询的帖子的postmeta,或者有一种方法可以避免进行如此多的查询?

1 个回复
最合适的回答,由SO网友:windyjonas 整理而成

这是一种获取帖子的postmeta的方法,方法是加入postmeta表并获取_wp_attached_file 元值。

尝试以下操作:

$mydb->get_results( select a.*, thumb.meta_value 
from wp_posts a 
left join (select b.post_id, c.meta_value 
from wp_postmeta b, wp_postmeta c 
where b.meta_key = \'_thumbnail_id\' 
and b.meta_value = c.post_id 
and c.meta_key = \'_wp_attached_file\') as thumb 
on thumb.post_id = a.ID 
where a.post_type = \'post\' 
and a.post_status = \'publish\', OBJECT );