Snippets Library

Related Posts by Category

Posted by Editorial Staff

To display related posts by category in WordPress without using a plugin, you can use the following code snippet:

<?php
// Get the current post's categories
$categories = get_the_category();
if ($categories) {
// Get the first category
$category = $categories[0];
$category_id = $category->term_id;
// Query for related posts
$args = array(
'post__not_in' => array(get_the_ID()), // Exclude the current post
'posts_per_page' => 5, // Number of related posts to display
'cat' => $category_id, // Only show posts from the same category
'orderby' => 'rand' // Random order
);
$related_query = new WP_Query($args);
// Output related posts
if ($related_query->have_posts()) {
echo '<ul class=check-list>';
while ($related_query->have_posts()) {
$related_query->the_post();
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
echo '</ul>';
}
// Reset post data
wp_reset_postdata();
}
?>

You can place this code in your theme file, such as single.php or content-single.php, where you want to display the related posts. This code fetches the current post’s categories, selects the first category, and queries for three random posts from the same category, excluding the current post. It then outputs the related posts in an unordered list (<ul>).

Please note that if you plan to use this code in multiple locations or want more flexibility, it’s recommended to create a custom function or shortcode to encapsulate the logic and make it easier to reuse.

Add CSS

Certainly! Here’s an example of a CSS style that you can apply to the related posts list to make it visually appealing:

.check-list {
padding: 0px;
margin: 0px;
list-style: none;
}
.check-list a {
text-decoration: none;
color: black;
margin-left: 26px;
}
.check-list a:hover {
text-decoration: underline;
color: #3787ff;
}
.check-list li {
position: relative;
padding-left: 1rem;
margin-bottom: 0.5rem;
}
/** Tick **/
.check-list li:before {
content: "'';
display: block;
position: absolute;
width: 8px;
height: 14px;
border-width: 0 2px 2px 0;
border-style: solid;
border-color: #00a8a8;
transform-origin: bottom left;
transform: rotate(44deg);
}

This CSS style adds a bullet symbol tick before each related post item, provides a slight margin between the items, and changes the color and text decoration on hover to enhance the user experience. Feel free to adjust the CSS properties as per your design preferences.

Preview

Leave a Reply

Your email address will not be published. Required fields are marked *