尊敬的Wordpress社区:,
我的工作现在似乎很艰难。我们有一个写文章的博客,还有一个写视频的博客,我现在必须制作一个列表,按顺序排列。分页。这就是我所尝试的:
switch_to_blog(1);
$query = (new WP_Query([
\'post_type\' => \'video\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 30,
\'paged\' => 1,
\'s\' => \'s\',
\'orderby\' => \'date\',
\'order\' => \'DESC\'
]))->posts;
以及:
switch_to_blog(2);
$query = (new WP_Query([
\'post_type\' => \'article\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 30,
\'paged\' => 1,
\'s\' => \'s\',
\'orderby\' => \'date\',
\'order\' => \'DESC\'
]))->posts;
问题是,输出当然不正确。两个结果集只能是
appended 不
merged. 最好是:
switch_to_blog([1,2]);
$query = (new WP_Query([
\'post_type\' => \'article\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 30,
\'paged\' => 1,
\'s\' => \'s\',
\'orderby\' => \'date\',
\'order\' => \'DESC\'
]))->posts;
但据我所知,这是不可能的。那怎么办?
SO网友:bueltge
您无法使用在网络的不同博客中切换switch_to_blog([1,2]);
作用对于一个blog,该函数需要一个明确的整数值,请参见documentation.
WP Core这个过程应该对您有所帮助。借助WP core的自定义方式。
// The sites IDs
$sitesObj = get_sites([
\'site__in\' => [1, 2,]
]);
// Merge
$sites = object_to_array( $sitesObj );
$args = [
\'post_type\' => \'post\',
\'posts_per_page\' => 2,
];
// The loop
foreach ($sites as $site) {
switch_to_blog( $site[\'blog_id\'] );
$loop = new WP_Query($args);
if ( $loop->have_posts() ) {
while ( ($loop->have_posts() ) : $loop->the_post();
// content
endwhile;
}
restore_current_blog();
}
您还可以使用自定义函数解决方案,如Eric的解决方案-
https://github.com/ericandrewlewis/WP_Query_Multisite 解决方案有很好的文档记录。
这种方式有点小,但您需要将此解决方案作为插件或包含在主题中。
$query = new WP_Query_Multisite( array( \'post_type\' => \'post\' ) );
while( $query->have_posts() ) : $query->the_post();
echo $blog_id . get_the_title() . "<br>";
endwhile;
wp_reset_postdata();