WordPress 多站点建站教程(六):使用WP_Query、switch_to_blog函数实现获取子站点分类中的文章

十度 wordpress 2015年12月01日 收藏

首先在你使用主题的funtions.php里面添加下代码:

  1. //根据时间显示最新的分类文章内容,每个站点显示一篇内容
  2. //$blog_id 子站点ID
  3. //$catid 分类ID
  4. wp_reset_query();
  5. switch_to_blog($blog_id);
  6. global $post;?>
  7. $my_query2 = new WP_Query('showposts=1&order=desc&orderby=date&cat='.$catid);
  8. while ($my_query2->have_posts()) : $my_query2->the_post();

 

接下来获取分类ID号,使用方法是

 

  1. global $wpdb;
  2. $most_viewed_cat = $wpdb->get_results("SELECT * from $wpdb->blogs");
  3. foreach ($most_viewed_cat as $keyc => $vc)
  4. {
  5. if($vc->blog_id !=1) //排除主站点ID
  6. {
  7. $id_cat[$keyc] = $vc->blog_id;
  8. }
  9. }
  10. $newid = array_flip($id_cat);
  11. $new_array_cat = array_rand($newid,10);
  12. $n_post = array_filter($new_array_cat);
  13. foreach ($n_post as $ksc => $volsc)
  14. {
  15. $most_cat = $wpdb->get_results("SELECT * from wp_".$volsc."_terms where name = '最新博文'");
  16. foreach ($most_cat as $ks => $vs)
  17. {
  18. get_cat_blogposts_wpmu($volsc,$vs->term_id); //方法调用
  19. }
  20. }