Advertisement
Guest User

Related Posts in WordPress (Doing many queries)

a guest
Dec 24th, 2012
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.46 KB | None | 0 0
  1. <?
  2.     function get_related_posts($max_results = 4) {
  3.  
  4.         # Back up old $posts and $post variables, as get_posts will change those
  5.         global $post, $posts;
  6.         $post_backup = $post;
  7.         $posts_backup = $posts;
  8.  
  9.         # Get terms from our custom taxonomy
  10.         $terms = get_the_terms($post->ID , 'my-cusotm-taxonomy');
  11.        
  12.         # Create arrays to hold our already-added posts and the result of this function
  13.         $do_not_duplicate[] = $post->ID;
  14.         $total_matches = array();
  15.  
  16.         # Make sure there are any taxonomy terms we can loop through.
  17.         if(!empty($terms) AND !is_wp_error($terms)) {
  18.            
  19.             # Loop over each term and do a new get_posts query for posts matching that term
  20.             foreach ($terms as $term) {
  21.                 $posts = get_posts(array(
  22.                     'post_type' => 'news',
  23.                     'custom-tag' => $term->slug,
  24.                     'posts_per_page' => 4,
  25.                     'post__not_in' => $do_not_duplicate,
  26.                 ));
  27.  
  28.                 # If any posts are found by that query,
  29.                 # add them to $do_not_duplicate, so they won't be added again later,
  30.                 # then push them into our $total_matches array
  31.                 if($posts) {
  32.                     foreach ($posts as $post) {
  33.                         $do_not_duplicate[] = $post->ID;
  34.                         array_push($total_matches, $post);
  35.                     }
  36.                 }
  37.             }
  38.  
  39.             # If we found any related posts above, show them.
  40.             if (count($total_matches) > 0)
  41.                 $total_matches = array_slice($total_matches, 0, $max_results);
  42.         }
  43.                
  44.         # Restore backups
  45.         $post = $post_backup;
  46.         $posts = $posts_backup;
  47.        
  48.         # Return result
  49.         return $total_matches;
  50.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement