WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Pulling posts from another site (6 posts)

  1. Bill Dennen
    Member
    Posted 2 years ago #

    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.

  2. Ron Rennick
    MultiSite Guru
    Posted 2 years ago #

    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/

  3. Bill Dennen
    Member
    Posted 2 years ago #

    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.

  4. The difference being that the site option does not automatically expire

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

  5. Bill Dennen
    Member
    Posted 2 years ago #

    Thank you.

  6. Ron Rennick
    MultiSite Guru
    Posted 2 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic