Come mostrare sotto ogni post in WordPress 3 post casuali?

  

4
Argomento iniziale

Ho un sito WordPress e sotto ogni articolo (post) voglio mostrare 3 articoli (post) casuali in modo da poter collegare tutti i miei post. Voglio che questo sia un codice semplice, mostrato solo come testo cliccabile, niente di particolare...

Potete aiutarmi per favore?

Forse qualche codice in functions.php?

Grazie

2 risposte
3

Nel tema Child in functions.php aggiungere queste righe di codice:

/* Shortcode for random posts */
/* The shortcode to put in any post/widget is [my-random-posts] */
function my_rand_posts() {
 
    $args = array(
        'post_type'      => 'post',
        'orderby'        => 'rand',
        'posts_per_page' => 3,
    );
 
    $the_query = new WP_Query($args);
    $string = "";
    if ($the_query->have_posts()) {
        $string .= '<ul>';
        while ($the_query->have_posts()) {
            $the_query->the_post();
            $string .= '<li><a href="' . get_permalink() . '" target="_blank">' . get_the_title() . '</a></li>';
        }
        $string .= '</ul>';
        /* Restore original Post Data */
        wp_reset_postdata();
    } else {
        $string .= 'no posts found';
    }
 
    return $string;
}
 
add_shortcode('my-random-posts', 'my_rand_posts');
add_filter('widget_text', 'do_shortcode');

Questo codice creerà uno shortcode che potrete inserire quando vorrete! Alla riga #8 (posts_per_page) è possibile scegliere il numero di post da visualizzare - nel nostro caso: 3. 

Lo shortcode da inserire in qualsiasi post/widget è: [my-random-posts]

Buon divertimento!

2

È anche possibile creare un proprio plugin per WP al fine di per mantenere il codice e lo shortcode nel caso in cui si cambi il tema della WordPress.

Ecco il codice del mio plugin WordPress che mostra gli ultimi 3 post (con le date alla fine 🙂 utilizzando lo shortcode: [my-plugin-recent-posts]:

<?php
 
/*
Plugin Name: My plugin recent posts shortcode
Plugin URI:  https://mypluginrecentpostsshortcode.com 
Description: WP plugin for showing recent posts with a shortcode
Author: My plugin recent posts shortcode Ltd.
Version: 1.0
Author URI:  https://mypluginrecentpostsshortcode.com 
Text Domain: my-plugin-recent-posts-shortcode
Domain Path: /languages/
 */
 
function my_plugin_recent_posts_shortcode() {
    $buffer = '<h4>Recent Posts:</h4><ul>';
 
    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 3,
    );
 
    $q = new WP_Query( $args );
 
    while ( $q->have_posts() ) {
        $q->the_post();
        $buffer .= '<li><a href=" ' . get_the_permalink() . '">' . get_the_title() . '</a> - ' . get_the_date() . ' </li>';
    }
    wp_reset_postdata();
 
    $buffer .= '</ul>';
 
    return $buffer;
}
 
add_shortcode( 'my-plugin-recent-posts', 'my_plugin_recent_posts_shortcode' );

...e questa è la schermata del mio blog WordPress:

il mio shortcode per i post recenti del plugin wordpress

Condividi: