Support » Networking WordPress » Pulling posts from another site

  • Resolved Bill Dennen

    (@xyzzy)


    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: http://pastebin.com/eGimhbGy

    Thanks.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Ron Rennick

    (@wpmuguru)

    MultiSite Guru

    Instead of using a transient use a site (network) option. The difference being that the site option does not automatically expire. You only need to generate a new version of the posts when a new post is published.

    See my network wide menu for some code for caching & refreshing when a post is edited/saved: http://wpmututorials.com/plugins/networkwide-menu/

    Thanks Ron. I’ve been reading up on the differences between transients, wp_cache, and options. It seems like any one of them would do, to some degree.

    You recommended options. Why not wp_cache? thanks again.

    Moderator Ipstenu (Mika Epstein)

    (@ipstenu)

    🏳️‍🌈 Halfelf Rogue & Plugin Review Team Rep

    The difference being that the site option does not automatically expire

    If your cache expires, everything gets recached, which causes duplication.

    Thank you.

    Ron Rennick

    (@wpmuguru)

    MultiSite Guru

    Site options are also cached so it isn’t an issue of cached vs non-cached.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Pulling posts from another site’ is closed to new replies.