WordPress: creare un elenco di post con il numero di commenti

WordPress: creare un elenco di post con il numero di commenti

È semplice in WordPress creare un elenco di post con il numero di commenti.

La seguente funzione utilizza le funzioni per la gestione del database di WordPress (come l'oggetto wpdb) per mostrare i post recenti ed il numero di commenti ad essi associati.

Aggiungete il codice al file functions.php:


function show_recent_articles() {
	global $wpdb;

	$args = array(
		'posts_per_page' => 30,
		'orderby' => 'date'
  );
	$loop = new WP_Query( $args );
  $html = '<div id="recent-posts"><h3>Recent posts</h3>';
  $html .= '<ul>';
        
  while( $loop->have_posts() ) {

		$loop->the_post();
		$id = get_the_ID();

		$comments = $wpdb->get_row( "SELECT comment_count as count FROM $wpdb->posts WHERE ID = '$id'" );
		$comments_no = $comments->count;

    $html .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a><small>' . get_the_date() . '</small><div>' .
		$comments_no . ' comments</div></li>';

  }
  
  wp_reset_postdata();
  
	$html .= '</ul></div>';

	echo $html;

}

Quindi potete aggiungere la funzione show_recent_articles() al vostro tema:


<?php show_recent_articles();?>

Torna su