Skip to content

Instantly share code, notes, and snippets.

@BigWhale
Last active June 29, 2019 09:08
Show Gist options
  • Save BigWhale/abacb924f17db8fdff05ee943cd5aa8a to your computer and use it in GitHub Desktop.
Save BigWhale/abacb924f17db8fdff05ee943cd5aa8a to your computer and use it in GitHub Desktop.
WordPress - get related posts by post tags
// Add this to your single.php or somewhere else where you see fit. :)
//
$post_id = get_the_ID();
// Extract post tags
$tags = get_the_terms( $post_id, 'post_tag' );
$tag_list = wp_list_pluck( $tags, 'term_id' );
$tag_list = implode( ',', $tag_list );
// Select post ID's from term_relationships table and order by those that match the most number of tags
$query = "SELECT DISTINCT object_id, COUNT(object_id) AS hit_count
FROM {$wpdb->prefix}term_relationships
WHERE object_id <> {$post_id} AND term_taxonomy_id IN ({$tag_list}) GROUP BY object_id ORDER BY hit_count DESC";
$posts = $wpdb->get_results( $query, ARRAY_A );
$post_list = wp_list_pluck( $posts, 'object_id' );
// Make a standard WP_Query and get relevant posts
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'post__not_in' => array( $post_id ), // Redundant, but you can never be too sure, right? ;)
'post__in' => $post_list,
'orderby' => 'rand',
'date_query' => array(
'after' => date('Y-m-d', strtotime('-1 year'))
)
);
$related = new WP_Query( $args );
// Perform the loop magic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment