Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

James Home
James Home
12,011 Points

WordPress related posts with the same taxonomy, but not the current post

I am trying to query other posts with the same taxonomy but to exclude the current post (of a custom post type).

I used an excellent post on Stack Overflow (http://stackoverflow.com/questions/21088161/wordpress-wp-query-related-posts-based-on-taxonomy#21088299) and used it for my purpose, and have tried to exclude the current post with "post__not_in" as you can see from the below code however it does not seem to work.

<?php
$post_terms = wp_get_object_terms($post->ID, 'article_tag', array('fields'=>'ids'));

$args = array(
    'post_type' => 'article',
    'tax_query' => array(
        array(
            'taxonomy' => 'article_tag',
            'field' => 'id',
            'terms' => $post_terms,
            'post__not_in' => array($post->ID)
        )
    )
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
        echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        ?>
                    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php
    }
        echo '</ul>';
} else {
    console.log("No related posts found.");
}
wp_reset_postdata();
?>

1 Answer

Yojance Rabelo
Yojance Rabelo
1,156 Points

I see 2 errors in code preventing this from working. Both are in the Tax Query.

First, it should be term_id instead of id for the field parameter

Second, 'post__not_in' => array($post->ID) should be moved outside of the Tax Query