On trouve souvent, à la fin d’un article, des articles connexes, permettant à l’utilisateur de continuer la lecture en conseillant des articles traitant du même sujet.

Afin de faire cela, on ajoute dans functions.php ou template-tags.php si le fichier existe, une petite fonction que l’on appelle à la fin dans single.php du thème.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
/** * Related posts */ function prefix_related_posts() { global $post; $terms = get_the_terms( $post->ID, 'category' ); $term_ids = []; if( is_array( $terms) ) { foreach( $terms as $term ) { $terms_ids[] = $term->term_id; } } $related_posts_query = new WP_Query( [ 'tax_query' => [ [ 'taxonomy' => 'category', 'field' => 'id', 'terms' => $term_ids, 'operator' => 'IN', ], ], 'post_type' => 'post', 'posts_per_page' => '4', 'orderby' => 'rand', 'post__not_in' => array( $post_id ), ] ); if( $related_posts_query->have_posts() ) : ob_start(); ?> <div id="related-posts"> <h3><?php _e('Related Posts', 'divi-child' ); ?></h3> <ul id="related-list"> <?php while( $related_posts_query->have_posts() ): $related_posts_query->the_post(); ?> <li class="hover"> <div class="related-thumb"> <a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail( 'medium' ); ?></a> </div> <div class="related-content"> <h4><a href="<?php the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h4> <p><?php the_time('j M Y') ?></p> </div> </li> <?php endwhile; ?> </ul> </div> <?php echo ob_get_clean(); endif; wp_reset_query(); } |
On formate le HTML comme on veut, mais la requète est la même et basée sur les articles dans la même catégorie. Celle-ci renvoie 4 articles.
Le CSS peut se présenter comme cela :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/* Related Pots */ div#related-posts { margin-top: 75px; } ul#related-list { list-style: none; padding: 0 !important; } ul#related-list h6 { padding: 0; line-height: 1.25; text-align: justify; margin: 0; } ul#related-list h6 a { color: #666666; } ul#related-list h6 a:hover { color: #2EA3F2; } ul#related-list p { font-size: 60%; text-align: right; margin: 5px 0 0 !important; color: #bbbbbb; } .related-thumb { text-align: center; } .related-content { padding: 0 5px; } ul#related-list li { clear: left; width: 49%; display: inline-block; border: 1px solid #DFDFDF; } |
On appelle simplement la fonction à la fin du fichier single.php, avant la fermeture de la div de la section primary.
Et hop, une petite fonction pour ajouter des articles connexes sans plugin.