Get All posts by tag in a network – wordpress multisite

If you want to show some selected posts as popular posts across the network, then this snippet is for you :) You can fetch posts by any tag that is available in your wordpress multisite network and show those to anywhere, maybe in the main site or in any subsite.

If you want to show posts from some selected subsites, you just need to pass those blog IDs as an array parameter or if you send an empty parameter it will fetch posts from all subsites in the network.

Here is the code:

You may also read:  Some Security Issue (php)
* Uses: get_tagged_post() or get_tagged_post( AN ARRAY OF BLOG IDs )
function get_tagged_post($blogs = array(), $tag) {
if( count( $blogs ) < 1 ){
$blog_list = wp_get_sites();
foreach ( $blog_list as $blog ) {
array_push( $blogs, $blog['blog_id'] );
$posts = array();
foreach( $blogs as $blog ){
switch_to_blog( $blog );
$args = array(
'tax_query' => array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $tag
$tagged_posts = get_posts( $args );
foreach( $tagged_posts as $tagged_post ){
array_push( $posts, array(
'title' => $tagged_post->post_title,
'link' => get_permalink( $tagged_post->ID )
) );
<ul class="tagged_posts">
<?php foreach( $posts as $post ) { ?>
<li><a href="<?php echo $post['link'] ?>"><?php echo $post['title']; ?></a></li>
<?php } ?>
get_tagged_post( array(), 'popular' );
You may also read:  How to hide a plugin for non-admin users in wordpress

view raw


hosted with ❤ by GitHub

You can add those codes in your functions.php in the theme, if you think your theme won’t be changed. Otherwise mu-plugins is the best solution. To use mu-plugins, go to /wp-content/ and find the folder with name ‘mu-plugins’. If there is no folder in that name, then create a folder, name it ‘mu-plugins’, create a file inside that, give any name you like and paste the code in there. You don’t need to activate that plugin. Mu-plugins means must use plugins, so it will be activated automatically always. If you use mu-plugins then add a php start tag at the beginning of the code. And then use the function in anywhere :)

You may also like...

Leave a Reply

%d bloggers like this: