WordPress, articoli correlati senza plugin

Oggi volevo aggiungere la sezione “articoli correlati” sotto ogni post e anziché usare uno dei tanti plugin presenti su WordPress.org, ho pensato di creare un piccolo mu-plugin adatto allo scopo.

<?php
/*
Plugin Name: Related Posts After Content
Plugin URI: https://salvatorenoschese.it/wordpress-articoli-correlati-senza-plugin
Description: Display related posts after the content of a single post.
Author: Salvatore Noschese
Author URI: https://salvatorenoschese.it
Version: 1.0
*/

// Hook the display_related_posts_after_content function into the the_content filter
add_filter('the_content', 'display_related_posts_after_content');
function display_related_posts_after_content($content) {
    // Check if it's a single post
    if (is_single()) {
        // Get the current post's categories
        $categories = get_the_category();

        if ($categories) {
            // Get the first category ID
            $category_id = $categories[0]->cat_ID;

            // Query related posts
            $related_posts = new WP_Query(array(
                'category__in' => array($category_id),
                'post__not_in' => array(get_the_ID()),
                'posts_per_page' => 3, // Adjust the number of related posts to display
                'orderby' => 'rand', // You can change the orderby parameter as per your preference
            ));

            // Display related posts
            if ($related_posts->have_posts()) {
                $related_content = '<p><strong>Vedi anche:</strong></p>';
                $related_content .= '<ul>';
                while ($related_posts->have_posts()) {
                    $related_posts->the_post();
                    $related_content .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
                }
                $related_content .= '</ul>';
                $related_content .= '<hr />';
                wp_reset_postdata();

                // Append related posts after the content
                $content .= $related_content;
            }
        }
    }

    return $content;
}

Il funzionamento è molto semplice (basta semplicemente piazzare il file nella solita cartella mu-plugins).

Risultato qui sotto in live ☺️

Fatemi sapere cosa ne pensate 👍


Iscriviti ai Feed dei commentirss small icon


Vedi anche:


Commenti

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *


go to top (svg)