0

Trying to build an easy "related posts" call, I would like to have it only shown, when another post has the exact same term and shows up.

It works at the moment so far, but also shows up, when the post is the only one with the exact term.

I am using

$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'related posts';
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'orderby'             => 'ASC',
'post__not_in' => array($post->ID),
'posts_per_page'=>2, // Number of related posts to display.
'caller_get_posts'=>1
);

$my_query = new wp_query( $args );
while( $my_query->have_posts() ) {
$my_query->the_post();

I am not getting it to work. Any help would be apreciated. Thank you.

1 Answer 1

0

You can and should do it in a more simple way:

In this example you can see the $tags variable, it get the tags of the post compare them and shows 7 posts (the showposts parameter) also makes sure that it won't show the original post (post__not_in parameter).

<?php // related posts based on first tag of current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {

    echo '<h3>Related Posts</h3>';

    $first_tag = $tags[0]->term_id;
    $args = array(
            'tag__in' => array($first_tag),
            'post__not_in' => array($post->ID),
            'showposts' => 7, // how many posts?
            'caller_get_posts' => 1
            );

    $my_query = new WP_Query($args);
    if ($my_query->have_posts()) { ?>

        <ul>

        <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>

            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

        <?php endwhile; ?>

        </ul>

    <?php } ?>
<?php } ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.