Advertisement
Guest User

Related posts in WordPress, using few queries

a guest
Dec 24th, 2012
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.98 KB | None | 0 0
  1. <?
  2.     function ns_get_related_posts($post, $post_type = 'post', $taxonomy = 'tag', $max_posts = null) {
  3.         $terms = get_the_terms($post->ID , $taxonomy);
  4.         $term_ids = array();
  5.         $result = array();
  6.  
  7.         # If max_posts isn't provided, fall back to global posts_per_page option
  8.         if ($max_posts == null) {
  9.             $max_posts = get_option('posts_per_page');
  10.         }
  11.        
  12.         # Map array of term ojects to an array of term ID's
  13.         if (!empty($terms)) foreach ($terms as $term) {
  14.             array_push($term_ids, $term->term_id);
  15.         }
  16.  
  17.         if (!empty($term_ids)) {
  18.             $related_posts = new WP_Query(array(
  19.                 'post_type' => $post_type,
  20.                 'posts_per_page' => $max_posts,
  21.                 'post__not_in' => array($post->ID),
  22.                 'tax_query' => array(array(
  23.                     'taxonomy' => $taxonomy,
  24.                     'field' => 'id',
  25.                     'terms' => $term_ids
  26.                 ))
  27.             ));
  28.  
  29.             if($related_posts->have_posts()) {
  30.                 foreach ($related_posts->posts as $related_post) {
  31.                     array_push($result, $related_post);
  32.                 }
  33.             }
  34.         }
  35.  
  36.         return $result;
  37.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement