Skip to content

Instantly share code, notes, and snippets.

@magadanskiuchen
Last active December 20, 2015 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magadanskiuchen/6049479 to your computer and use it in GitHub Desktop.
Save magadanskiuchen/6049479 to your computer and use it in GitHub Desktop.
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