我有一个类似的问题。我需要获取所有网络站点上按评论排序的帖子列表(以显示最受欢迎的帖子)。这是我使用的功能。
其基础是,它首先获取网络中所有博客ID的列表。然后,它构建一个大的单个查询(使用UNION合并所有行,而不需要难看的JOIN),该查询将获得包含blog_id,ID和comment_count列的结果。然后,我使用get_blog_post()获取每个帖子的详细信息。
您可以在不同的地方使用一些调试行来查看正在发生的事情。
function txx_top_posts_mu( $howMany = 10 ) {
global $wpdb;
global $table_prefix;
// get an array of the table names that our posts will be in
// we do this by first getting all of our blog ids and then forming the name of the
// table and putting it into an array
$rows = $wpdb->get_results( "SELECT blog_id from $wpdb->blogs WHERE
public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0';" );
if ( $rows ) :
$blogPostTableNames = array();
foreach ( $rows as $row ) :
$blogPostTableNames[$row->blog_id] = $wpdb->get_blog_prefix( $row->blog_id ) . 'posts';
endforeach;
//print_r($blogPostTableNames);
// now we need to do a query to get all the posts from all our blogs
// ordered by the number of comments and with limits applied
if ( count( $blogPostTableNames ) > 0 ) :
$query = '';
$i = 0;
foreach ( $blogPostTableNames as $blogId => $tableName ) :
if ( $i > 0 ) :
$query.= ' UNION ';
endif;
$query.= " SELECT ID, comment_count, $blogId as `blog_id` FROM $tableName ";
$i++;
endforeach;
$query.= " ORDER BY comment_count DESC LIMIT 0,$howMany;";
//echo $query;
$rows = $wpdb->get_results( $query );
// now we need to get each of our posts into an array and return them
if ( $rows ) :
$posts = array();
foreach ( $rows as $row ) :
$posts[] = get_blog_post( $row->blog_id, $row->ID );
endforeach;
//print_r($posts);
return $posts;
endif;
endif;
endif;
return false;
}