+261 34 15 417 90 contact@creawebagency.com

How to display related posts in WordPress without plugins ?

191 vue(s)

Sharing is caring!

You are developing a wordpress site and you want to display similar articles (related posts)? There are some plugins that can do this, but to avoid installing a plugin we will show you how to set up this system manually.

In my case, I use wordpress and Bootstrap so we will display similar articles on a line with 3 columns. Don’t worry even site you are new to the code. To do this, simply paste the following code into the single.php file of your child theme.

<div class="container">
<div class="row">
<?php $categories = get_the_category($post->ID); ?>
<?php if ($categories): ?>
<?php $category_ids = array(); ?>
<?php foreach($categories as $individual_category) : ?>
<?php $category_ids[] = $individual_category->term_id; ?>
<?php endforeach; ?>
<?php $args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'oderby' => 'rand'
<?php $my_query = new WP_Query($args); ?>
<?php if( $my_query->have_posts() ) : ?>
<section class="container">
<h3 style="text-transform: normal; font-weight: 400;">Vous aimerez aussi :</h3>

<div class="row">
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div class="col-md-4">

<a href="<?php the_permalink()?>" class="related-thumb"><?php the_post_thumbnail(); ?></a>
<h4 class="title-like"><a href="<?php the_permalink()?>"><?php the_title(); ?></a></h4>

<?php endwhile;?>

<?php endif; ?>
<?php wp_reset_query();?>
<?php endif; ?>

Results (see picture)



Dans la même catégorie :