|
<?php |
|
/* |
|
Plugin Name: Speckyboy Related Posts |
|
Plugin URI: https://speckyboy.com/ |
|
Description: Displays related posts based on categories and tags at the bottom of each post. |
|
Version: 1.0 |
|
Author: Eric Karkovack |
|
Author URI: https://karks.com/ |
|
License: GPL2 |
|
*/ |
|
|
|
if (!defined('ABSPATH')) exit; // Exit if accessed directly |
|
|
|
function rpd_get_related_posts($post_id) { |
|
$categories = wp_get_post_categories($post_id); |
|
$tags = wp_get_post_tags($post_id, array('fields' => 'ids')); |
|
|
|
if (empty($categories) && empty($tags)) { |
|
return []; // No categories or tags, return empty array |
|
} |
|
|
|
$args = [ |
|
'post_type' => 'post', |
|
'post_status' => 'publish', |
|
'posts_per_page' => 4, |
|
'post__not_in' => [$post_id], |
|
'orderby' => 'rand', |
|
'tax_query' => [ |
|
'relation' => 'OR', |
|
] |
|
]; |
|
|
|
if (!empty($categories)) { |
|
$args['tax_query'][] = [ |
|
'taxonomy' => 'category', |
|
'field' => 'term_id', |
|
'terms' => $categories, |
|
]; |
|
} |
|
|
|
if (!empty($tags)) { |
|
$args['tax_query'][] = [ |
|
'taxonomy' => 'post_tag', |
|
'field' => 'term_id', |
|
'terms' => $tags, |
|
]; |
|
} |
|
|
|
$query = new WP_Query($args); |
|
return $query->posts; |
|
} |
|
|
|
function rpd_display_related_posts($content) { |
|
if (!is_single() || !in_the_loop() || !is_main_query()) { |
|
return $content; |
|
} |
|
|
|
global $post; |
|
$related_posts = rpd_get_related_posts($post->ID); |
|
|
|
if (empty($related_posts)) { |
|
return $content; |
|
} |
|
|
|
$output = '<div class="related-posts"><h3>Related Posts</h3><ul>'; |
|
foreach ($related_posts as $related) { |
|
$output .= '<li><a href="' . get_permalink($related->ID) . '">' . esc_html(get_the_title($related->ID)) . '</a></li>'; |
|
} |
|
$output .= '</ul></div>'; |
|
|
|
return $content . $output; |
|
} |
|
add_filter('the_content', 'rpd_display_related_posts'); |