wordpress获取相关文章的方法


当读者在看你的文章时,如果我们能在我们的文章末尾添加该文章的相关文章推荐,这样不仅对读者有一个更全面了解该文章的相关信息,也能提高我们网站的访问量,本文将介绍wordpress中获取相关文章的方法:
将以下代码添加到我们主题的functions.php文件中,各个部分功能都有注释:

  1. // 根据文章分类读取相关文章
  2. function wptuts_more_from_cat( $title = "相关文章:" ) {
  3. global $post;
  4. // 显示第一个分类的相关文章
  5. $categories = get_the_category( $post->ID );
  6. $first_cat = $categories[0]->cat_ID;
  7. // 标题
  8. $output = '<div id="more-from-cat"><h3>' . $title . '</h3>';
  9. // 参数设置
  10. $args = array(
  11. // 分类设置
  12. 'category__in' => array( $first_cat ),
  13. // 排除的文章ID
  14. 'post__not_in' => array( $post->ID ),
  15. // 显示文章数,默认为5
  16. 'posts_per_page' => 5
  17. );
  18. // 通过 get_posts() 函数获取数据
  19. $posts = get_posts( $args );
  20. if( $posts ) {
  21. $output .= '<ul>';
  22. // 开始循环
  23. foreach( $posts as $post ) {
  24. setup_postdata( $post );
  25. $post_title = get_the_title();
  26. $permalink = get_permalink();
  27. $output .= '<li><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '">' . $post_title . '</a></li>';
  28. }
  29. $output .= '</ul>';
  30. } else {
  31. // 当没有相关分类文章显示如下
  32. $output .= '<p>抱歉,暂无相关文章!/p>';
  33. }
  34. // div结束
  35. $output .= '</div>';
  36. return $output;
  37. }

OK,然后打开我们的文章页模板single.php 文件,然后调用以上方法来获取分类相关文章

  1. <?php echo wptuts_more_from_cat( '相关文章:' ); ?>