WordPress教程

WordPress 怎样获取同分类下文章的上一篇与下一篇

阿里云

一般我们获取 wordpress 文章的上下篇都是用 get_previous_post()与 get_next_post()函数来获取,那么如何获取同分类下的上下篇文章呢,只需要给这俩函数加一个参数即可。

  1. get_previous_post(true)
  2.  
  3. get_next_post(true)
也想出现在这里?联系我们
创客主机

即可,获取到的就是一个 post 对象。

这里获取到的是分类 1 or 2 的文章,如果你想获取分类 1 and 2 的文章,那么得这样。

  1. // Create a new filtering function that will add our where clause to the query
  2. function date_filter_where( $where = '' ) {
  3. global $post;
  4. $where .= " AND post_date >= '".$post->post_date."'";
  5. return $where;
  6. }
  7.  
  8. //then create your own get previous post function which will take an array of categories eg: 
  9. // $cats = array('1','2');
  10. function my_get_previous_post($cats){
  11. global $post;
  12. $temp = $post;
  13. $args = array(
  14. 'posts_per_page' => 1,
  15. 'post_type' => 'post',
  16. 'post_status' => 'publish',
  17. 'category__and' => $cats
  18. );
  19. add_filter( 'posts_where','date_filter_where' );
  20. $q = new WP_Query($args);
  21. remove_filter( 'posts_where','date_filter_where' );
  22. while ($q->have_posts()){
  23. $q->the_post;
  24. echo '<a href="'.get_permalink($post->ID).'">'.get_the_title($post->ID).'</a>';
  25. }
  26. $post = $temp;
  27. wp_reset_query();
  28. }

使用$cats = array('1','2'); my_get_previous_post($cats);

WordPress 怎样获取同分类下文章的上一篇与下一篇

已有 136 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!