WordPress: creare un elenco di post da una categoria casuale

WordPress: creare un elenco di post da una categoria casuale

È semplice in WordPress creare un elenco di post da una categoria casuale.

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 codice nel file functions.php:


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 .= '<ul id="random-posts">';
	
	if( $loop->have_posts() ) {
	
		while( $loop->have_posts() ) {
		
			$loop->the_post();
			
			$html .= '<li class="random-post">';
			$html .= '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
			$html .= '<p>' . get_the_excerpt() . '</p>';
			$html .= '</li>';
		
		
		}
	
	  wp_reset_postdata();
	}
	
	$html .= '</ul>';
	
	return $html;
}

Quindi potete inserire la funzione appena definita nel vostro tema:


<?php echo get_posts_from_random_category(); ?>

Torna su