Related posts by tags except the specified tag (3 posts)

  1. Dolomats0
    Posted 2 years ago #


    I m stuck and need help, so until now i m able to show related posts by

    But i i want to exclude a tag from it EX:

    i want show all related post that have similar tag and execlude the
    tag (USA per exemple from the comparison

    here is the code that i m using

                                $args = array();
                                $cats = array();
                                $categories = get_the_tags();
                                foreach($categories as $cat)
                                    $cats[] = $cat->term_id;
                                $args['tag__in'] = $cats;
                                $args['post__not_in'] = (array)$post->ID;
                                $args['posts_per_page'] = 3;
                                $args['orderby'] = 'rand';
                                $query = new WP_Query($args);
                                while($query->have_posts() ) : $query->the_post(); ?>
                                    <div class="column">
                                        <div class='inner'>
                                            <a href="<?php the_permalink();?>">

    i hope i was clear thank you

  2. Shaun Scovil
    Posted 2 years ago #

    I think I get what you are asking...you want to exclude posts from a particular tag, yeah?

    If so, try this:

        $include = wp_list_pluck( get_the_tags(), 'term_id' );
        $exclude = array( 123 ); // ID of tag to exclude
        $args = array(
            'tag__in'        => $include,
            'tag__not_in'    => $exclude,
            'post__not_in'   => array( $post->ID ),
            'posts_per_page' => 3,
            'orderby'        => 'rand'
        $query = new WP_Query($args);
        while( $query->have_posts() ) : $query->the_post();
        <!-- Inside the loop. -->

    You just have to set the $exclude variable to the ID of the tag(s) you want to exclude.

  3. Dolomats0
    Posted 2 years ago #

    Thanks for answer but how can i insert this code iside my code

    because the code i added on my post up is the one who show the related post in my single page so i can change it i can only edit it !

    Thank you

Topic Closed

This topic has been closed to new replies.

About this Topic