La soluzione per mostrare post presi da una categoria casuale è semplice in WordPress.
La seguente funzione utilizza la funzione get_categories() per estrarre un valore casuale dall'array di categorie restituito e quindi usare tale valore per selezionare una categoria casuale e i suoi post.
Inserite il codice nel file functions.php
:
function my_get_posts_from_random_category() {
$cat = 1;
$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 ) );
if( $loop->have_posts() ) {
$html .= '<div id="random-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>';
}
wp_reset_postdata();
$html .= '</div>';
}
return $html;
}
Quindi potete inserire la funzione appena definita nel vostro tema:
<?php echo my_get_posts_from_random_category(); ?>