WP Query related posts by tags

I want to display related posts ordered by multiple tags.
So I need to create a function what will query posts with the most number of tags in common and display them in descending order. But also it need to display all other posts (which don’t have tags which are in current posts or don’t have tags at all) but in the end of the list. I found the code that almost did the job, but it does not display posts what does not contain current post tags (as I said before I need these posts at the end of the query result

function exe_get_related_posts_by_common_terms( $post_id, $number_posts = 0, $taxonomy = ‘post_tag’, $post_type = ‘post’ ) {
global $wpdb;

$post_id = (int) $post_id;
$number_posts = (int) $number_posts;

$limit = $number_posts > 0 ? ‘ LIMIT ‘ . $number_posts : ”;

$related_posts_records = $wpdb->get_results(
“SELECT tr.object_id, count( tr.term_taxonomy_id ) AS common_tax_count
FROM {$wpdb->term_relationships} AS tr
INNER JOIN {$wpdb->term_relationships} AS tr2 ON tr.term_taxonomy_id = tr2.term_taxonomy_id
INNER JOIN {$wpdb->term_taxonomy} as tt ON tt.term_taxonomy_id = tr2.term_taxonomy_id
INNER JOIN {$wpdb->posts} as p ON p.ID = tr.object_id
tr2.object_id = %d
AND tt.taxonomy = %s
AND p.post_type = %s
GROUP BY tr.object_id
HAVING tr.object_id != %d
ORDER BY common_tax_count DESC” . $limit,
$post_id, $taxonomy, $post_type, $post_id

if ( count( $related_posts_records ) === 0 )
return false;

$related_posts = array();

foreach( $related_posts_records as $record )
$related_posts[] = array(
‘post_id’ => (int) $record->object_id,
‘common_tax_count’ => $record->common_tax_count

return $related_posts;

Can anyone help me to make this sql query work? Thank you!

Read more here:: WP Query related posts by tags

Leave a Reply

Your email address will not be published. Required fields are marked *