Quando si usa la funzionalità Multisite di WordPress il nostro database si arricchisce di una nuova gerarchia tra le tabelle che lega la tabella dei blog a quella dei post contenuti in ciascuno di essi. In questo articolo vedremo come visualizzare i post più recenti presi da ciascuno dei blog presenti nella nostra installazione.
Per prima cosa, aggiungiamo la seguente funzione al file functions.php
:
function recent_mu_posts( $many = 10 ) {
global $wpdb;
global $table_prefix;
$rows = $wpdb->get_results( "SELECT blog_id from $wpdb->blogs WHERE
public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0';" );
if ( $rows ) :
$blogPostTableNames = array();
foreach ( $rows as $row ) :
$blogPostTableNames[$row->blog_id] = $wpdb->get_blog_prefix( $row->blog_id ) . 'posts';
endforeach;
if ( count( $blogPostTableNames ) > 0 ) :
$query = '';
$i = 0;
foreach ( $blogPostTableNames as $blogId => $tableName ) :
if ( $i > 0 ) :
$query.= ' UNION ';
endif;
$query.= " (SELECT ID, post_date, $blogId as `blog_id` FROM $tableName WHERE post_status = 'publish' AND post_type = 'post')";
$i++;
endforeach;
$query.= " ORDER BY post_date DESC LIMIT 0,$many;";
echo $query;
$rows = $wpdb->get_results( $query );
if ( $rows ) :
$posts = array();
foreach ( $rows as $row ) :
$posts[] = get_blog_post( $row->blog_id, $row->ID );
endforeach;
return $posts;
endif;
endif;
endif;
return false;
}
Questa funzione restituisce un array contenente gli ID dei post presi dai vari blog. Possiamo quindi usare la funzione nel nostro tema o con uno shortcode:
$posts = recent_mu_posts();
foreach ($posts as $post) {
setup_postdata($post);
// Continua il Loop
}