Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Shows related posts by tag if available and category if not
  5. *
  6. * @author Justin Tallant
  7. * @param string $title h4 above list of related posts
  8. * @param int $count max number of posts to show
  9. * @return mixed related posts wrapped in div or null if none found
  10. */
  11. function jt_related_posts($title = 'Related Posts', $count = 5) {
  12.  
  13. global $post;
  14.  
  15. $tag_ids = array();
  16.  
  17. $current_cat = get_the_category($post->ID);
  18. $current_cat = $current_cat[0]->cat_ID;
  19. $this_cat = '';
  20.  
  21. $tags = get_the_tags($post->ID);
  22.  
  23. if ( $tags ) {
  24. foreach($tags as $tag) {
  25. $tag_ids[] = $tag->term_id;
  26. }
  27. } else {
  28. $this_cat = $current_cat;
  29. }
  30.  
  31. $args = array(
  32. 'post_type' => get_post_type(),
  33. 'numberposts' => $count,
  34. 'orderby' => 'rand',
  35. 'tag__in' => $tag_ids,
  36. 'cat' => $this_cat,
  37. 'exclude' => $post->ID
  38. );
  39.  
  40. $related_posts = get_posts($args);
  41.  
  42. /**
  43. * If the tags are only assigned to this post try getting
  44. * the posts again without the tag__in arg and set the cat
  45. * arg to this category.
  46. */
  47. if ( empty($related_posts) ) {
  48. $args['tag__in'] = '';
  49. $args['cat'] = $current_cat;
  50. $related_posts = get_posts($args);
  51. }
  52.  
  53. if ( empty($related_posts) ) {
  54. return;
  55. }
  56.  
  57. $post_list = '';
  58.  
  59. foreach($related_posts as $related) {
  60. $post_list .= '<li><a href="' . get_permalink($related->ID) . '">' . $related->post_title . '</a></li>';
  61. }
  62.  
  63. return sprintf('
  64. <div class="related-posts">
  65. <h4>%s</h4>
  66. <ul>%s</ul>
  67. </div> <!-- .related-posts -->
  68. ', $title, $post_list );
  69. }
  70.  
  71. /**
  72. * Customize the title and where the related posts are displayed
  73. */
  74. add_action('genesis_after_post_content', 'do_jt_related_posts');
  75. function do_jt_related_posts() {
  76.  
  77. $title = 'Related Posts';
  78.  
  79. if ( !is_single() ) {
  80. return;
  81. }
  82.  
  83. if ( get_post_type() == 'gallery' || get_post_type() == 'case-studies' ) {
  84. $title = 'See more client sites';
  85. }
  86.  
  87. /**
  88. * Array of post types to be excluded
  89. */
  90. $exclude = array('aeprofiles', 'bizdir', 'palettes');
  91.  
  92. foreach($exclude as $type) {
  93. if ( get_post_type() == $type ) {
  94. return;
  95. }
  96. }
  97.  
  98. echo jt_related_posts($title);
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement