WordPress主题调用多站点文章代码
WordPress主题调用多站点文章代码
要在WordPress主题中调用多站点的文章,你可以使用WordPress的switch_to_blog和restore_current_blog函数来实现。以下是一个简单的示例代码:
<?php
// 定义要调用的站点ID列表
$site_ids = array(1, 2, 3); // 替换为你自己的站点ID
// 循环遍历站点ID列表
foreach ($site_ids as $site_id) {
switch_to_blog($site_id);
// 构建文章查询参数
$args = array(
'posts_per_page' => 5, // 显示的文章数量
'ignore_sticky_posts' => 1
);
// 执行文章查询
$posts = new WP_Query($args);
// 输出文章
if ($posts->have_posts()) {
echo '<h2>站点 ' . $site_id . ' 的文章</h2>';
echo '<ul>';
while ($posts->have_posts()) {
$posts->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
}
// 恢复原始查询的状态
wp_reset_postdata();
restore_current_blog();
}
?>
将上述代码添加到你的WordPress主题的合适位置,它会遍历指定的多个站点,并在每个站点上执行文章查询。然后,它将输出每个站点的文章列表。
请注意,上述代码仅是一个简单示例,你可以根据自己的需求进行修改和扩展。确保在使用代码之前备份你的主题文件,并根据你的多站点设置进行相应的调整。
此外,请确保在使用switch_to_blog函数切换到不同的站点之后,使用restore_current_blog函数将环境切换回原始站点,以确保正确的数据和状态恢复。