function related_posts_by_exact_category_shortcode() {
global $post;
// Ensure we are on a single post page
if (!is_single() || !$post) {
return ”;
}
// Get the current post categories
$categories = get_the_category($post->ID);
if (!$categories) {
return ‘
No related posts found.
‘;
}
// Get all category IDs of the current post
$category_ids = array_map(function($category) {
return $category->term_id;
}, $categories);
// Get the ID of the “ultimas” category (replace ‘ultimas’ with the actual slug)
$ultima_category = get_category_by_slug(‘ultimas’); // ‘ultimas’ is the correct slug
if ($ultima_category) {
// Remove the “ultimas” category ID from the category list entirely
$category_ids = array_diff($category_ids, array($ultima_category->term_id));
}
// Query related posts only from the same categories (excluding “ultimas”)
$args = array(
‘category__in’ => $category_ids, // Only show posts from the exact same categories (excluding “ultimas”)
‘post__not_in’ => array($post->ID), // Exclude the current post
‘posts_per_page’ => 4, // Show 4 related posts
‘orderby’ => ‘rand’, // Show random posts
);
$query = new WP_Query($args);
$output = ”;
if ($query->have_posts()) {
$output .= ‘
$output .= ‘
‘; // Close grid and wrapper
}
wp_reset_postdata();
return $output;
}
// Register the shortcode
add_shortcode(‘related_posts’, ‘related_posts_by_exact_category_shortcode’);
// Add CSS for 4-column grid layout
function related_posts_styles() {
echo ‘
‘;
}
add_action(‘wp_head’, ‘related_posts_styles’);





