WordPress: visualizzare i post di una categoria casuale
Possiamo visualizzare i post presi da una categoria casuale utilizzando una semplice tecnica per WordPress.
Visualizzare gli ultimi post presi da una categoria casuale è un ottimo modo per far convergere l’attenzione del lettore su degli argomenti non troppo popolari nel nostro sito in WordPress. Possiamo definire una funzione nel nostro file functions.php per eseguire questo compito. Vediamo come.
Possiamo usare la funzione get_categories() per ottenere un array contenente tutte le categorie in uso sul nostro sito. Quindi possiamo creare un indice casuale con cui estrarre l’ID della categoria corrente. Nell’esempio ho usato 0 come primo parametro della funzione PHP mt_rand(). Ovviamente dovreste calibrare il range di valori in base agli ID delle vostre categorie:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
function get_posts_from_random_category() {
$cat = '';
$html = '';
$categories = get_categories();
$index = mt_rand(0, count($categories));
$cat = $categories[$index]->term_id;
$loop = new WP_Query(array('cat' => $cat, 'posts_per_page' => 3));
$html .= '<div id="random-posts">';
if($loop->have_posts()) {
while($loop->have_posts()) {
$loop->the_post();
$html .= '<div class="random-post">';
$html .= '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
$html .= '<p>' . get_the_excerpt() . '</p>';
$html .= '</div>';
}
}
$html .= '</div>';
return $html;
} |
Potete quindi usare questa funzione nel vostro tema come segue:
|
1 |
<?php echo get_posts_from_random_category(); ?> |

Nessun commento. Aggiungine uno!
I commenti sono chiusi.