Incluir una relación de post relacionados al final de nuestros artículos ayuda a la navegación transversal por nuestro blog y ofrece información posiblemente de interés a los usuarios.
Hay plugins o temas de wordpress que incluyen esta funcionalidad. Sin embargo, también es posible hacerlo sin necesidad de instalar nada más.
En el blog de DECODECMS nos explican cómo (https://decodecms.com/posts-relacionados-sin-plugins-en-wordpress/)
Ello lo hacemos a través del fichero functions.php de nuestro tema.
Es importante que trabajemos con un tema hijo, o con cada actualización perderemos el código.
Incluir función en el archivo functions.php
El archivo functions.php se encuentra en la carpeta de nuestro tema (o tema-hijo). También podemos editarlo a través de la interfaz de wordrpess en Apariencia > Editor.
Podemos hacer la relación de los post a través de:
- Categorías
- Tags o etiquetas.
Post relacionados por categoría
El código es el siguiente:
/*
Función para post relacionados a través de categorías
*/
function related_after_content( $content )
{
if ( !is_singular('post') ) return $content;
$cad = "";
$template_li = '<li>
<a class="thumb_rel" href="{url}">{thumb}</a>
<a class="title_rel" href="{url}">{title}</a>
</li>';
$template_rel = '<div class="rel_posts">
<h3>Artículos Relacionados</h3>
<ul>
{list}
</ul>
</div>';
$terms = get_the_terms( get_the_ID(), 'category');
$categ = array();
if ( $terms )
{
foreach ($terms as $term)
{
$categ[] = $term->term_id;
}
}
else{
return $content;
}
$loop = new WP_QUERY(array(
'category__in' => $categ,
'posts_per_page' => 4,
'post__not_in' =>array(get_the_ID()),
'orderby' =>'rand'
));
if ( $loop->have_posts() )
{
while ( $loop->have_posts() )
{
$loop->the_post();
$search = Array('{url}','{thumb}','{title}');
$replace = Array(get_permalink(),get_the_post_thumbnail(),get_the_title());
$cad .= str_replace($search,$replace, $template_li);
}
if ( $cad )
{
$content .= str_replace('{list}', $cad, $template_rel);
}
}
wp_reset_query();
return $content;
}
add_filter( 'the_content', 'related_after_content');
Post relacionados por tags
El código es el siguiente:
<?php
function related_after_content( $content )
{
if ( !is_singular('post') ) return $content;
$cad = "";
$template_li = '<li>
<a class="thumb_rel" href="{url}">{thumb}</a>
<a class="title_rel" href="{url}">{title}</a>
</li>';
$template_rel = '<div class="rel_posts">
<h3>Artículos Relacionados</h3>
<ul>
{list}
</ul>
</div>';
$terms = get_the_terms( get_the_ID(), 'post_tag');
$tags = array();
if ( $terms ){
foreach ($terms as $term)
{
$tags[] = $term->term_id;
}
}
else{
return $content;
}
$loop = new WP_QUERY(array(
'tag__in' => $tags,
'posts_per_page' => 4,
'post__not_in' =>array(get_the_ID()),
'orderby' =>'asc'
));
if ( $loop->have_posts() )
{
while ( $loop->have_posts() )
{
$loop->the_post();
$search = Array('{url}','{thumb}','{title}');
$replace = Array(get_permalink(),get_the_post_thumbnail(),get_the_title());
$cad .= str_replace($search,$replace, $template_li);
}
if ( $cad )
{
$content .= str_replace('{list}', $cad, $template_rel);
}
}
wp_reset_query();
return $content;
}
add_filter( 'the_content', 'related_after_content');
Aplicar estilo CSS al bloque de post relacionados
Podemos aplicar estilo al nuevo bloque de artículos relacionados a través de estilo CSS. Para ello, simplemente añadimos la personalización al fichero CSS del tema.
Un ejemplo es el siguiente:
.rel_posts {
border-top: 1px dotted gray;
padding-top: 20px;
}
.rel_posts:after {
content: "";
display: block;
margin-bottom: 10px;
padding-bottom: 10px;
clear: both;
}
.rel_posts ul {
width: 100%;
margin-left:0px;
}
.rel_posts ul li {
list-style: none;
width: 20%;
float: left;
margin-left: 20px;
}
.rel_posts ul li .title_rel {
display: block;
padding: 4px;
}
@media only screen and (max-width: 600px) {
.rel_posts ul li {
width: 40%;
margin-left: 15px;
margin-bottom: 15px;
}
.rel_posts ul li:nth-child(odd) {
clear: both;
}
}
El resultado es similar a lo siguiente:

