How to: Related Posts with Thumbnails in WordPress without Plugins

4 days ago, WordPress Themes, Views
How to: Related Posts with Thumbnails in WordPress Without Plugins

Introduction: Beyond Plugins for Related Posts

WordPress is a powerful platform, and while plugins offer extended functionality, sometimes the best approach is to dive into the code and achieve your desired results without relying on external additions. This article guides you through implementing related posts with thumbnails in WordPress without using any plugins. We’ll explore the necessary PHP code modifications and CSS styling to achieve a professional and efficient related posts section.

Understanding the Fundamentals

Before we begin, let’s clarify what we aim to achieve. We want to display a list of posts related to the current article being viewed. The relationship will be determined by shared categories and tags. Each related post will be displayed with a thumbnail image, title, and potentially an excerpt. This will enhance user engagement and encourage exploration of your website’s content.

Step 1: Modifying Your Theme’s `functions.php` File

The core logic for fetching related posts will reside within your theme’s `functions.php` file. This file is crucial for customizing your theme’s functionality. Always remember to back up your `functions.php` file before making any changes, as errors can break your website.

Open your theme’s `functions.php` file. You can access this file through your WordPress admin panel by navigating to Appearance -> Theme Editor (Appearance -> Editor for Block Themes), and selecting `functions.php` from the list of theme files on the right. Insert the following code snippet at the end of the file, but before the closing `?>` tag (if present):

“`php
term_id;
}

$category_ids = array();
if ($categories) {
foreach($categories as $individual_category) $category_ids[] = $individual_category;
}

$args = array(
‘post_type’ => ‘post’,
‘posts_per_page’ => $number_of_posts,
‘post__not_in’ => array($post_id),
‘ignore_sticky_posts’ => 1,
‘orderby’ => ‘date’,
‘order’ => ‘DESC’,
‘tax_query’ => array(
‘relation’ => ‘OR’,
array(
‘taxonomy’ => ‘post_tag’,
‘field’ => ‘term_id’,
‘terms’ => $tag_ids
),
array(
‘taxonomy’ => ‘category’,
‘field’ => ‘term_id’,
‘terms’ => $category_ids
)
)
);

$related_posts = new WP_Query($args);

if ($related_posts->have_posts()) {
echo ‘

‘;
wp_reset_postdata();
}
}
}

?>
“`

Let’s break down this code:

  • `get_related_posts_with_thumbnails($post_id, $number_of_posts = 5)`: This defines a function that takes the current post ID and an optional number of posts to display (defaulting to 5).
  • `wp_get_post_tags($post_id)` and `wp_get_post_categories($post_id)`: These functions retrieve the tags and categories associated with the current post.
  • `$args` array: This array defines the query arguments for fetching related posts. It specifies the post type, number of posts, exclusion of the current post, ordering by date, and a `tax_query` that retrieves posts sharing the same tags or categories.
  • `WP_Query($args)`: This creates a new WordPress query based on the defined arguments.
  • The `while` loop iterates through the related posts and displays each one with a thumbnail, title, and a link to the post. A default thumbnail is shown if no featured image is set.
  • `wp_reset_postdata()`: This is important to reset the global `$post` object to the main query after running a custom query.

Step 2: Integrating the Function into Your Theme’s Template

Now that you’ve defined the function, you need to call it within your theme’s template file, typically `single.php` (or a similar file responsible for displaying single posts). This is where the related posts section will appear on your website.

Locate the `single.php` file in your theme’s directory (Appearance -> Theme Editor). Find the place where you want to display the related posts – usually after the main content of the post but before the comments section. Insert the following PHP code snippet:

“`php

“`

This code checks if the `get_related_posts_with_thumbnails` function exists (to prevent errors if the function wasn’t properly defined) and then calls the function, passing the current post ID as an argument.

Step 3: Styling with CSS

The HTML structure generated by the PHP function includes CSS classes like `related-posts`. We’ll use these classes to style the related posts section and its elements. Add the following CSS code to your theme’s `style.css` file (or use your theme’s custom CSS option if it has one):

“`css
.related-posts {
margin-top: 30px;
border-top: 1px solid #eee;
padding-top: 20px;
}

.related-posts h3 {
font-size: 20px;
margin-bottom: 15px;
}

.related-posts ul {
list-style: none;
padding: 0;
margin: 0;
display: flex; /* Added for horizontal layout */
flex-wrap: wrap; /* Allow items to wrap to the next line */
}

.related-posts li {
width: calc(50% – 10px); /* Two items per row, adjust as needed */
margin-right: 20px; /* Space between items */
margin-bottom: 20px;
}

.related-posts li:nth-child(2n) { /* Remove right margin for every second item */
margin-right: 0;
}

.related-posts a {
display: block;
text-decoration: none;
color: #333;
}

.related-posts img {
width: 100%;
height: auto;
margin-bottom: 5px;
border-radius: 5px;
}

.related-posts span {
display: block;
font-size: 14px;
line-height: 1.4;
}
“`

This CSS provides basic styling for the related posts section, including:

  • Margins and padding for spacing.
  • Font size for the heading.
  • Removal of list bullets.
  • Flexible layout for the list items, displaying them in multiple columns.
  • Styling for the links, images, and text.

Feel free to customize these styles to match your theme’s design.

Step 4: Handling Default Thumbnails

The code includes a placeholder for a default thumbnail image when a post doesn’t have a featured image. You need to create an image named `default-thumbnail.jpg` and place it in your theme’s `images` directory (or modify the path in the code to reflect the actual location of your default image). This ensures that all related posts have a visual representation, even if they lack a featured image.

Customization and Further Enhancements

The code provided is a starting point. You can customize it further to meet your specific needs:

  • Adjust the number of related posts displayed by modifying the `$number_of_posts` variable in the function call.
  • Modify the criteria for determining relatedness (e.g., prioritize tags over categories).
  • Add an excerpt or other information to the related posts.
  • Implement different styling for different screen sizes using media queries in your CSS.

Conclusion: Embracing Code for Control

By implementing related posts with thumbnails without relying on plugins, you gain greater control over your website’s functionality and reduce the potential for plugin conflicts and bloat. This approach may require a bit more technical knowledge, but the benefits of improved performance and customization outweigh the initial effort. Remember to always back up your files before making changes and test thoroughly to ensure everything functions as expected. This method is a testament to the power and flexibility of WordPress when you venture beyond the realm of plugins and embrace the underlying code.