annelyse
12/4/2017 - 4:46 PM

Displayed related post with the same tag

/**
 * display related post (with same tags)
 */

function related_posts_by_tags() { 
    global $post;
    $tags = wp_get_post_tags($post->ID);

    if ($tags) {
        $tagArray = array();
        foreach($tags as $tag){
            $tagArray[] = $tag->slug;
        }

        $args=array(
            'post_type' => 'post',
            'tag' => $tagArray,
            'post__not_in' => array($post->ID),
            'posts_per_page' => 2
           
        );
        $my_query = new WP_Query($args);
        if( $my_query->have_posts() ) {
            echo '<div class="row related_posts">';
            echo '<h2 class="col-12 title">Les articles en relation</h2>';
            while ($my_query->have_posts()) : $my_query->the_post(); 
            echo '<div class="col-md-6 col-lg-12">';
            get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format());
            echo '</div>';
            endwhile;
            echo '</div>';
        }
        wp_reset_query();
    }
}