WordPress.org

Forums

Loop, not plugin, to list related posts by tag (4 posts)

  1. samsugar
    Member
    Posted 7 years ago #

    I'm trying to add related posts to my single.php template. For various reasons, mostly flexibility, I don't want to use a related posts plugin.

    I want to be able to list a fixed number of posts, which use any of the tags used in the main post on a single post page, in reverse chronological order. I'm trying to write a second loop to do it.

    I've written this code but it's not working:

    <?php $posttags = get_the_tags();
    if ($posttags) {
    foreach($posttags as $tag) {
    $sep = ( $tags ) ? ',' : '';
    $tags .= $sep . '\'' . $tag->name . '\'';
       }
    };
    ?>
    
    <?php $my_query = new WP_Query("showposts=4&tag=$posttags");
    while ($my_query->have_posts()) : $my_query->the_post();
    $do_not_duplicate = $post->ID; ?>
    	<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><br />
    <?php endwhile; ?>

    I cribbed the first chunk from here, http://wordpress.pastebin.ca/869461. It's code which should do what I want, but chooses posts at random - which I don't want. For some reason I can't get it to work at all - even without modification.

    Please help and no - I don't want to use a plugin. I've tried them and they don't work.

    Thanks in advance.

  2. manx
    Member
    Posted 6 years ago #

    Hi I’m searching for the same solution. Have you solved it?

  3. TheGreatBundini
    Member
    Posted 6 years ago #

    Another bump. I've been trying to do the same thing for the last two hours.

  4. Dunkkan
    Member
    Posted 6 years ago #

    Here there's a quite cool code but is still in a beta phase, and the author search for contributors.

    http://wordpress.org/support/topic/219641?replies=3

Topic Closed

This topic has been closed to new replies.

About this Topic