Want to get posts from sites in Multisite in WordPress? Use following code in your theme’s functions.php file OR in site specific plugin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | // Get current blog $original_blog_id = get_current_blog_id(); // Setup a category for each blog id you want to loop through - EDIT $catslug_per_blog_id = array( 1 => 'video', 4 => 'news' ); foreach( $catslug_per_blog_id as $bid => $catslug ) { //Switch to the blog with the blog id $bid switch_to_blog( $bid ); // Get posts for each blog $myposts = get_posts( array( 'category_name' => $catslug, 'posts_per_page' => 2, ) ); // Skip a blog if no posts are found if( empty( $myposts ) ) continue; // Loop for each blog $li = ''; global $post; foreach( $myposts as $post ) { setup_postdata( $post ); $li .= the_title( $before = sprintf( '<li><a href="%s">', esc_url( get_permalink() ) ), $after = '</a></li>', $echo = false ); } // Print for each blog printf( '<h2>%s (%s)</h2><ul>%s</ul>', esc_html( get_bloginfo( 'name' ) ), esc_html( $catslug ), $li ); } // Switch back to the current blog switch_to_blog( $original_blog_id ); wp_reset_postdata(); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.