How to Display Related Posts in WordPress Without Plugin

Rate this post

How to Display Related Posts in WordPress Without Plugin

Introduction

Displaying related posts on your WordPress site is a fantastic way to keep visitors engaged, reduce bounce rates, and improve your site’s overall user experience. However, many WordPress users rely heavily on plugins to achieve this, which can sometimes slow down a website or introduce compatibility issues. Fortunately, you don’t need a plugin to display related posts.

This guide will show you how to display related posts in WordPress without a plugin, using simple coding techniques. By the end of this article, you’ll have a customized related posts section that not only enhances your website’s functionality but also aligns with your site’s design.

Why Display Related Posts?

Before diving into the how-to, it’s essential to understand why you should consider displaying related posts on your WordPress site. Related posts help:

  • Improve User Engagement: By suggesting content similar to what the visitor is currently reading, you increase the chances of them staying on your site longer.
  • Boost SEO: Related posts can reduce bounce rates and increase the number of pages a visitor views, which can positively impact your site’s SEO.
  • Increase Page Views: Showing related posts encourages visitors to explore more of your content, leading to higher page views.
  • Build a Cohesive User Experience: By linking related content, you create a more seamless and enjoyable browsing experience.

Now that we’ve established the benefits, let’s dive into how you can display related posts in WordPress without a plugin.

1. Using WordPress Functions to Display Related Posts

WordPress provides several built-in functions that allow you to display related posts without needing a plugin. The get_posts() function is one such example. Here’s a basic implementation to display related posts based on the category of the current post.

Step-by-Step Guide

1. Open Your Theme’s Single Post Template: Start by accessing the single.php file in your theme’s directory. This is where you’ll add the code to display related posts.

2. Insert the Code: Add the following code snippet to the bottom of the single.php file, just above the closing <?php endwhile; ?> tag.

<?php
$categories = get_the_category($post->ID);
if ($categories) {
    $category_ids = array();
    foreach ($categories as $individual_category) {
        $category_ids[] = $individual_category->term_id;
    }

    $args = array(
        'category__in' => $category_ids,
        'post__not_in' => array($post->ID),
        'posts_per_page' => 5,
        'caller_get_posts' => 1
    );

    $related_posts = get_posts($args);
    if ($related_posts) {
        echo '<h3>Related Posts</h3><ul>';
        foreach ($related_posts as $post) {
            setup_postdata($post);
            ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php
        }
        echo '</ul>';
    }
    wp_reset_postdata();
}
?>

3. Customize the Appearance: You can style the related posts list by adding custom CSS to your theme’s style.css file. This allows you to align the appearance with your site’s overall design.

4. Save and Test: Save the changes and view a post on your site to see the related posts in action.

This method uses the categories assigned to a post to find related posts. You can easily modify it to use tags or custom taxonomies instead.

2. Displaying Related Posts Based on Tags

If you prefer to show related posts based on tags rather than categories, you can modify the above code slightly. Tags can often provide a more specific connection between posts, making this a good alternative.

Implementing the Code

1. Modify the Code: Replace the $categories' part with $tags' and adjust the rest accordingly.

<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
    $tag_ids = array();
    foreach ($tags as $individual_tag) {
        $tag_ids[] = $individual_tag->term_id;
    }

    $args = array(
        'tag__in' => $tag_ids,
        'post__not_in' => array($post->ID),
        'posts_per_page' => 5,
        'caller_get_posts' => 1
    );

    $related_posts = get_posts($args);
    if ($related_posts) {
        echo '<h3>Related Posts</h3><ul>';
        foreach ($related_posts as $post) {
            setup_postdata($post);
            ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php
        }
        echo '</ul>';
    }
    wp_reset_postdata();
}
?>

2. Add CSS Styling: As with the category-based method, you can style the related posts section using CSS in your style.css file.

3. Test the Changes: After saving the file, check your site to ensure the related posts based on tags are displaying correctly.

3. Customizing the Related Posts Output

Displaying related posts in WordPress without a plugin offers a great deal of flexibility, allowing you to customize how the posts are displayed. Whether you want to change the number of posts shown, display thumbnails, or add excerpts, this can all be done with some modifications to the code.

Showing Thumbnails with Related Posts

To make your related posts section more visually appealing, you can add post thumbnails. WordPress makes it easy to include thumbnails with the the_post_thumbnail() function.

1. Modify the Code: Update your existing related posts code to include the thumbnail function.

<?php
$categories = get_the_category($post->ID);
if ($categories) {
    $category_ids = array();
    foreach ($categories as $individual_category) {
        $category_ids[] = $individual_category->term_id;
    }

    $args = array(
        'category__in' => $category_ids,
        'post__not_in' => array($post->ID),
        'posts_per_page' => 5,
        'caller_get_posts' => 1
    );

    $related_posts = get_posts($args);
    if ($related_posts) {
        echo '<h3>Related Posts</h3><ul>';
        foreach ($related_posts as $post) {
            setup_postdata($post);
            ?>
            <li>
                <a href="<?php the_permalink(); ?>">
                    <?php if (has_post_thumbnail()) {
                        the_post_thumbnail('thumbnail');
                    } ?>
                    <?php the_title(); ?>
                </a>
            </li>
            <?php
        }
        echo '</ul>';
    }
    wp_reset_postdata();
}
?>

2. Style the Thumbnails: Ensure the thumbnails are sized and positioned correctly using CSS. You might want to define a specific size for the thumbnails by adding a new image size in your theme’s functions.php file:

add_image_size('related-post-thumb', 120, 120, true);

3. Test and Adjust: Save your changes, then view a post on your site to see how the related posts appear with thumbnails.

4. Displaying Related Posts Using Custom Queries

For more advanced users, custom WP_Query allows for even greater control over how related posts are displayed. This method is particularly useful if you have specific criteria that you want to base related posts on.

Creating a Custom WP_Query

1. Add the Query: Replace the 'get_posts()' function with a custom 'WP_Query'.

<?php
$args = array(
    'category__in' => wp_get_post_categories($post->ID),
    'post__not_in' => array($post->ID),
    'posts_per_page' => 5,
    'orderby' => 'rand'
);

$related_posts_query = new WP_Query($args);

if ($related_posts_query->have_posts()) {
    echo '<h3>Related Posts</h3><ul>';
    while ($related_posts_query->have_posts()) : $related_posts_query->the_post(); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
    <?php endwhile;
    echo '</ul>';
}

wp_reset_postdata();
?>

2. Customize the Query: You can modify the ‘$args' array to include or exclude specific post types, authors, or even custom fields.

3. Test the Output: After saving, review your changes on your site to ensure the related posts are displaying as expected.

5. Using Custom Taxonomies for Related Posts

If your site uses custom taxonomies, you can display related posts based on those as well. This method is particularly useful for niche sites where categories and tags might not be sufficient.

Implementing the Code

1. Identify Your Custom Taxonomy: Determine the custom taxonomy you want to use for related posts.

2. Modify the Code: Replace the category or tag-based code with custom taxonomy code.

<?php
$taxonomy = 'your_custom_taxonomy';
$terms = wp_get_post_terms($post->ID, $taxonomy);
if ($terms) {
    $term_ids = array();
    foreach ($terms as $individual_term) {
        $term_ids[] = $individual_term->term_id;
    }

    $args = array(
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy,
                'field' => 'term_id',
                'terms' => $term_ids,
            ),
        ),
        'post__not_in' => array($post->ID),
        'posts_per_page' => 5,
        'caller_get_posts' => 1
    );

    $related_posts = get_posts($args);
    if ($related_posts) {
        echo '<h3>Related Posts</h3><ul>';
        foreach ($related_posts as $post) {
            setup_postdata($post);
            ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php
        }
        echo '</ul>';
    }
    wp_reset_postdata();
}
?>

3. Style and Test: Ensure everything is styled appropriately and functioning as expected.

6. Displaying Related Posts in a Sidebar Widget

You might want to display related posts in a sidebar or other widget area. To do this without a plugin, you can use a custom function in your functions.php file and then call it in a widget area.

Adding a Custom Function

1. Add the Function to functions.php:

function related_posts_widget() {
    global $post;
    $args = array(
        'category__in' => wp_get_post_categories($post->ID),
        'post__not_in' => array($post->ID),
        'posts_per_page' => 5,
        'orderby' => 'rand'
    );

    $related_posts = get_posts($args);
    if ($related_posts) {
        echo '<h3>Related Posts</h3><ul>';
        foreach ($related_posts as $post) {
            setup_postdata($post);
            ?>
            <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php
        }
        echo '</ul>';
    }
    wp_reset_postdata();
}

2. Call the Function in a Widget Area: Edit your theme’s sidebar.php or use the WordPress Customizer’s Widgets section to add this function where you want the related posts to appear.

<?php if (is_single()) { related_posts_widget(); } ?>

3. Style and Test: Once added, you can style the widget using CSS to fit your theme.

7. Displaying Related Posts with a Custom Template

If you want full control over how and where related posts are displayed, creating a custom template is the way to go. This method is ideal for those who want to integrate related posts seamlessly into their theme’s design.

Creating a Custom Template

1. Create a New Template File: In your theme’s directory, create a new PHP file (e.g., related-posts-template.php).

2. Add the Related Posts Code: Add the related posts code of your choice (category-based, tag-based, custom taxonomy, etc.) into this new file.

<?php
/* Template Name: Related Posts */
get_header(); ?>

<div id="content">
    <?php
    if (have_posts()) :
        while (have_posts()) : the_post();

            the_content();

            // Related posts code here
            related_posts_widget();

        endwhile;
    endif;
    ?>
</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

3. Use the Template: When creating or editing a page in WordPress, you can now select this custom template to display related posts as part of that page.

4. Test and Refine: Make sure everything looks and works as expected.

Conclusion

Displaying related posts in WordPress without a plugin is not only possible but also allows for greater control and customization. By using WordPress functions, custom queries, and a bit of PHP, you can create a related posts section that perfectly fits your site’s design and improves user engagement. Whether you prefer category-based, tag-based, or custom taxonomy-based related posts, the methods outlined in this guide will help you achieve your goals.

If you have any questions or need further assistance with implementing related posts on your WordPress site, feel free to leave a comment below. I’d love to hear your thoughts and help you out!

Leave a Comment