• Hi all

    I have a function in my functions.php file to display 2 recommended posts by tag.

    function related_posts() {
        global $post;
        $tags = wp_get_post_tags( $post->ID );
        if($tags) {
            foreach( $tags as $tag ) {
                $tag_arr = $tag->slug . '';
            }
            $args = array(
                'tag' => $tag_arr,
                'numberposts' => 2, /* You can change this to show more */
                'post__not_in' => array($post->ID)
            );
            $related_posts = get_posts( $args );
    
            if($related_posts) {
    
            echo '<div class="related">';
            echo '<h2>More like this</h2>';
                foreach ( $related_posts as $post ) : setup_postdata( $post ); ?>
                <p><a href="<?php the_permalink();?>"><?php the_title();?></a></p>
                <?php endforeach;
    	     echo '</div>';
    	            }
                }
        wp_reset_postdata();
    }

    Unfortunately this code is not working. I’m not using it in the Loop, could this be why?

    It works sometimes but not other times, and when it does work sometimes it only shows 1 post when there are several.

    I would really appreciate some help!

  • The topic ‘Problem with related posts by tag using get_posts’ is closed to new replies.