Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get related posts by number of shared terms (WordPress). Update {POST_ID} and {TAXONOMY_NAME}
SELECT `posts`.`ID`, `posts`.`post_title`, COUNT(`posts`.`post_title`) AS `connections`
FROM `wp_posts` AS `posts`
INNER JOIN `wp_term_relationships` AS `term_rel` ON (`term_rel`.`object_id` = `posts`.`ID`)
INNER JOIN `wp_term_taxonomy` AS `term_tax` ON (`term_tax`.`term_taxonomy_id` = `term_rel`.`term_taxonomy_id`)
WHERE `term_rel`.`term_taxonomy_id` IN (
SELECT `term_rel`.`term_taxonomy_id`
FROM `wp_term_relationships` AS `term_rel`
WHERE `term_rel`.`object_id` = {POST_ID}
)
AND `term_tax`.`taxonomy` = '{TAXONOMY_NAME}'
AND `posts`.`ID` != {POST_ID}
GROUP BY `posts`.`post_title`
ORDER BY connections DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment