Pulling posts from another site
-
Hi there,
I’ve long wrestled with using switch_to_blog to pull from one blog and display them in another. I realize that there are other solutions for this (like RSS), but using switch_to_blog allows full access to the posts (featured thumbnails, custom fields), whereas RSS does not.
In this case, I’d like to switch to the WPMU sitewide tags site and pull the most recent posts from a certain category. My code pulls the posts, loops through them, and stores some generated HTML in a transient. (For now the lifetime of the transient is 5 minutes – likely to change):
Does this code seem fine, or is there a better way? Looking for suggestions.
// Get any existing copy of our transient data if ( false === ( $output = get_site_transient( 'wheaton_news_ticker' ) ) ) { $tags_blog_id = get_sitewide_tags_option( 'tags_blog_id' ); switch_to_blog( $tags_blog_id ); $ticker_query = new WP_Query('post_type=post&posts_per_page=10&category_name=news'); $output = ''; while ( $ticker_query->have_posts() ) : $ticker_query->the_post(); $blogid = get_post_meta( $post->ID, 'blogid', true ); $blogname = get_blog_option( $blogid,'blogname' ); $output .= '<li><a href="' . get_permalink() . '" title="' . esc_attr( get_the_excerpt() ) . '">' . esc_html( get_the_title() ) . ' [<span class="sitename">' . esc_html( $blogname ) . '</span>]</a></li>' . "\n"; endwhile; set_site_transient( 'wheaton_news_ticker', $output, 60 * 5 ); wp_reset_postdata(); restore_current_blog(); } echo $output ;
Code also here: https://pastebin.com/eGimhbGy
Thanks.
- The topic ‘Pulling posts from another site’ is closed to new replies.