Welcome to EasyCodingWithAI!

Before you dive into coding with AI, take a moment to consider some valuable insights. Our articles cover the pros and cons of using AI in development, the importance of having a development environment, and how AI empowers hobbyists and small businesses:

Post Icon

Tutorial : WordPress – Related Posts Shortcode

Posted by Richard Robins on October 29, 2024 - Last modified on October 30, 2024.

Overview

This guide provides detailed instructions on creating the EasyCodingWithAI – Related Posts Shortcode plugin for WordPress.

This plugin will enable the display of related posts based on shared categories.

Example Prompt:

Help me create a WordPress plugin called “EasyCodingWithAI – Related Posts Shortcode” that displays related posts with a customizable heading and responsive thumbnail sizes. The admin should be able to set the number of related posts displayed on mobile, tablet, and desktop, as well as select the thumbnail size from options like “thumbnail” or “medium.” The related posts should display based on shared categories and exclude the current post.

Step 1: Setting Up Your Plugin

  1. Create Plugin Folder:
    • In your WordPress installation, navigate to the wp-content/plugins directory.
    • Create a new folder named easycoding-related-posts.
  2. Create the Main Plugin File:
    • Inside the easycoding-related-posts folder, create a PHP file named easycoding-related-posts.php.
    • Add the following code to the file to define the plugin and include all necessary functionalities:
<?php
/*
Plugin Name: EasyCodingWithAI - Related Posts Shortcode
Description: Display related posts with medium-sized thumbnails and responsive styling.
Version: 1.2
Author: EasyCodingWithAI
*/

// Register settings for the AdminCP
function easycoding_register_settings() {
add_option('easycoding_related_posts_mobile_count', 2);
add_option('easycoding_related_posts_tablet_count', 4);
add_option('easycoding_related_posts_desktop_count', 6);
add_option('easycoding_related_posts_heading', 'You Might Be Interested In:'); // Default heading
add_option('easycoding_related_posts_thumbnail_size', 'thumbnail'); // Set to default thumbnail size

register_setting('easycoding_options_group', 'easycoding_related_posts_mobile_count');
register_setting('easycoding_options_group', 'easycoding_related_posts_tablet_count');
register_setting('easycoding_options_group', 'easycoding_related_posts_desktop_count');
register_setting('easycoding_options_group', 'easycoding_related_posts_heading'); // Register heading setting
register_setting('easycoding_options_group', 'easycoding_related_posts_thumbnail_size'); // Register thumbnail size setting
}
add_action('admin_init', 'easycoding_register_settings');

// Create AdminCP page
function easycoding_create_admin_page() {
add_options_page(
'Related Posts Settings', // Page title
'Related Posts', // Menu title in Settings
'manage_options', // Capability required
'easycoding-related-posts', // Menu slug
'easycoding_render_admin_page' // Function to display settings page
);
}
add_action('admin_menu', 'easycoding_create_admin_page');

// Render the AdminCP settings page
function easycoding_render_admin_page() {
?>
<div class="wrap">
<h1>Related Posts Settings</h1>
<form method="post" action="options.php">
<?php
settings_fields('easycoding_options_group');
do_settings_sections('easycoding_options_group');
?>
<table class="form-table">
<tr valign="top">
<th scope="row">Heading Text</th>
<td><input type="text" name="easycoding_related_posts_heading" value="<?php echo esc_attr(get_option('easycoding_related_posts_heading')); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Thumbnail Size</th>
<td><input type="text" name="easycoding_related_posts_thumbnail_size" value="<?php echo esc_attr(get_option('easycoding_related_posts_thumbnail_size')); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Number of Posts (Mobile)</th>
<td><input type="number" name="easycoding_related_posts_mobile_count" value="<?php echo esc_attr(get_option('easycoding_related_posts_mobile_count', 2)); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Number of Posts (Tablet)</th>
<td><input type="number" name="easycoding_related_posts_tablet_count" value="<?php echo esc_attr(get_option('easycoding_related_posts_tablet_count', 4)); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Number of Posts (Desktop)</th>
<td><input type="number" name="easycoding_related_posts_desktop_count" value="<?php echo esc_attr(get_option('easycoding_related_posts_desktop_count', 6)); ?>" /></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
}

// Function to check for tablet device (example logic; customize as needed)
function easycoding_is_tablet_device() {
return wp_is_mobile() && isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'Tablet') !== false;
}

// Shortcode function
function easycoding_related_posts_shortcode($atts) {
// Get count settings based on device type
if (wp_is_mobile() && !easycoding_is_tablet_device()) {
$count = get_option('easycoding_related_posts_mobile_count', 2);
} elseif (easycoding_is_tablet_device()) {
$count = get_option('easycoding_related_posts_tablet_count', 4);
} else {
$count = get_option('easycoding_related_posts_desktop_count', 6);
}

// Get the current post's ID
$current_post_id = get_the_ID();

// Get the current post's categories
$current_categories = get_the_category($current_post_id);
$category_ids = array();

// Extract category IDs
if (!empty($current_categories)) {
foreach ($current_categories as $category) {
$category_ids[] = $category->term_id;
}
}

if (empty($category_ids)) {
return ''; // Return empty if there's no category assigned
}

// Query for related posts with shared categories, excluding the current post
$args = array(
'post_type' => 'post',
'posts_per_page' => $count,
'post__not_in' => array($current_post_id),
'category__in' => $category_ids,
'orderby' => 'rand',
);

$related_posts = new WP_Query($args);

// Start output
$output = '<h3>' . esc_html(get_option('easycoding_related_posts_heading')) . '</h3><ul class="related-posts">';

if ($related_posts->have_posts()) {
while ($related_posts->have_posts()) {
$related_posts->the_post();
$output .= '<li>';
$output .= '<div class="related-thumbnail">';
// Check for the post thumbnail
if (has_post_thumbnail()) {
$thumbnail_size = get_option('easycoding_related_posts_thumbnail_size', 'thumbnail'); // Default to 'thumbnail' size
$thumbnail_url = get_the_post_thumbnail_url(null, $thumbnail_size);
$output .= '<a href="' . get_permalink() . '"><img src="' . esc_url($thumbnail_url) . '" alt="' . get_the_title() . '" /></a>';
}
$output .= '</div>'; // Close the related-thumbnail div

// Always show the title regardless of thumbnail existence
$output .= '<div class="related-title">';
$output .= '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
$output .= '</div>';

$output .= '</li>';
}
} else {
$output .= '<li>No related posts found.</li>';
}

// End output
$output .= '</ul>';

// Restore the global $post object
wp_reset_postdata();

return $output;
}
add_shortcode('related_posts', 'easycoding_related_posts_shortcode');
?>

Step 2: Creating the CSS File

  • Create the CSS File:
  • In the easycoding-related-posts folder, create a CSS file named easycoding-related-posts.css.
  • Add your CSS styles for the related posts. Here’s an example:
/* Style for the related posts container */
ul.related-posts {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-wrap: wrap;
}

/* Style for each related post item */
ul.related-posts li {
flex: 1;
margin: 10px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
text-align: center;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); /* Added shadow for depth */
border-radius: 4px; /* Rounded corners */
transition: transform 0.2s; /* Smooth scaling on hover */
}

ul.related-posts li:hover {
transform: scale(1.05); /* Scale effect on hover */
}

/* Style for the related post titles */
ul.related-posts li a {
text-decoration: none;
color: #333;
font-weight: bold;
}

/* Style for the related post thumbnails */
ul.related-posts li .related-thumbnail {
margin-top: 10px;
}

/* Ensure images are responsive */
ul.related-posts li .related-thumbnail img {
max-width: 100%; /* Responsive image */
height: auto; /* Maintain aspect ratio */
}

/* Media query for common mobile sizes */
@media (max-width: 599px) { /* Common mobile devices */
ul.related-posts li {
flex-basis: 100%; /* Full width on small screens */
}
}

/* Media query for common tablet sizes */
@media (min-width: 600px) and (max-width: 899px) { /* Common tablet devices */
ul.related-posts li {
flex-basis: calc(50% - 20px); /* Two items per row on tablets */
}
}

/* Media query for common desktop sizes */
@media (min-width: 900px) { /* Common desktop and larger screens */
ul.related-posts li {
flex-basis: calc(25% - 20px); /* Four items per row on desktops */
}
}

How to Activate the Plugin

After creating the EasyCodingWithAI – Related Posts Shortcode plugin, follow these steps to activate it:

  1. Log in to Your WordPress Admin Dashboard:
    • Go to your WordPress site and log in with your admin credentials.
  2. Navigate to the Plugins Section:
    • In the left sidebar, click on Plugins to view the installed plugins.
  3. Locate the EasyCodingWithAI – Related Posts Shortcode Plugin:
    • Find the EasyCodingWithAI – Related Posts Shortcode in the list of plugins.
  4. Activate the Plugin:
    • Click the Activate button below the plugin name to activate it.
  5. Configure Plugin Settings (Optional):
    • After activation, you can configure the plugin settings by navigating to Related Posts in the left sidebar. Here, you can set the number of related posts to display on mobile, tablet, and desktop, as well as customize the heading text.

How to Use the Related Posts Shortcode in Posts and Templates

Using the Shortcode in Posts

To display the related posts in your WordPress posts, simply add the following shortcode to the content editor where you want the related posts to appear:

[related_posts]

This will automatically fetch and display the related posts based on the shared categories of the current post.

Using the Shortcode in Templates

If you want to display the related posts in a template file (like single.php or page.php), you can use the following PHP code:

<?php echo do_shortcode('[related_posts]'); ?>

This line of code will execute the shortcode and display the related posts in the specified location within your template.


Richard Robins

Richard Robins

Richard is passionate about sharing how AI resources such as ChatGPT and Microsoft Copilot can be used to create addons and write code, saving small website owners time and money, freeing them to focus on making their site a success.


Disclaimer

The coding tips and guides provided on this website are intended for informational and educational purposes only. While we strive to offer accurate and helpful content, these tips are meant as a starting point for your own coding projects and should not be considered professional advice.

We do not guarantee the effectiveness, security, or safety of any code or techniques discussed on this site. Implementing these tips is done at your own risk, and we encourage you to thoroughly test and evaluate any code before deploying it on your own website or application.

By using this site, you acknowledge that we are not responsible for any issues, damages, or losses that may arise from your use of the information provided herein.