
Related Posts in WordPress (Doing many queries)
By: a guest on
Dec 24th, 2012 | syntax:
PHP | size: 1.46 KB | hits: 31 | expires: Never
<?
function get_related_posts($max_results = 4) {
# Back up old $posts and $post variables, as get_posts will change those
global $post, $posts;
$post_backup = $post;
$posts_backup = $posts;
# Get terms from our custom taxonomy
$terms = get_the_terms($post->ID , 'my-cusotm-taxonomy');
# Create arrays to hold our already-added posts and the result of this function
$do_not_duplicate[] = $post->ID;
$total_matches = array();
# Make sure there are any taxonomy terms we can loop through.
if(!empty($terms) AND !is_wp_error($terms)) {
# Loop over each term and do a new get_posts query for posts matching that term
foreach ($terms as $term) {
$posts = get_posts(array(
'post_type' => 'news',
'custom-tag' => $term->slug,
'posts_per_page' => 4,
'post__not_in' => $do_not_duplicate,
));
# If any posts are found by that query,
# add them to $do_not_duplicate, so they won't be added again later,
# then push them into our $total_matches array
if($posts) {
foreach ($posts as $post) {
$do_not_duplicate[] = $post->ID;
array_push($total_matches, $post);
}
}
}
# If we found any related posts above, show them.
if (count($total_matches) > 0)
$total_matches = array_slice($total_matches, 0, $max_results);
}
# Restore backups
$post = $post_backup;
$posts = $posts_backup;
# Return result
return $total_matches;
}