Support » Fixing WordPress » Related Posts Order by Tag Count

  • richarduk


    I’ve been beating my brains out on this and can’t get anywhere.

    The code below checks for tags in a post, then outputs any other posts that have any of those tags and are in the specified category.

    What I want to do is order the posts with the ones with the most tags in common first, on the grounds that they’re probably going to be the most relevant posts.

    I can count the tags easily enough for each post:

    $posttags = array();
    $posttags = get_the_tags();
    $count= count($posttags);

    I could then sort the array. However, I’m struggling beyond this e.g. associating each count with a post ID and then outputting the relevant post.

    I’m guessing I’ll need a second loop but I’m really floundering. I guess the second loop would contain something like this to start with, but it’s a wild guess:

    <?php $my_query2 = new WP_Query('');
    while ($my_query2->have_posts()) : $my_query2->the_post();
    $ordertags[] = $post->ID ?>

    Any help much appreciated.

    Here’s the basic code, based on MichaelH’s code here

    and also here

    $backup = $post;
    $tags = wp_get_post_tags($post->ID);
    $tagIDs = array();
    if ($tags) {
        		$tagcount = count($tags);
       		for ($i = 0; $i < $tagcount; $i++)
         			$tagIDs[$i] = $tags[$i]->term_id;
     $args=array( 'tag__in' => $tagIDs,'post__not_in' => array($post->ID), 'showposts'=>5, 'caller_get_posts'=>1, 'cat' => 23);
     $my_query = new WP_Query($args);
     if( $my_query->have_posts() )
        					while ($my_query->have_posts()) : $my_query->the_post(); ?>
        					<h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
      					<?   endwhile;
    else { ?>
    <h2>No related posts found!</h2>
     <?php }
     $post = $backup;
  • The topic ‘Related Posts Order by Tag Count’ is closed to new replies.