2

I am trying to write a function that will allow me to specify a post ID and a blog ID, and then have it return the permalink and title of the blog post.

I need this to be efficient because the function will be used in a foreach loop that could cause the function to run upwards of 50 times.

Any ideas?

4
  • You could use some form of caching ( with Transients for instance codex.wordpress.org/Transients_API) to cache the results in between? I'd suggest to first write the function before dealing with performance. See also: secure.wikimedia.org/wikipedia/en/wiki/…
    – BjornW
    Aug 23 '11 at 10:49
  • Thanks for that. Any idea on the performance issues caused by using switch_to_blog() ?
    – Pippin
    Aug 23 '11 at 13:58
  • Hey @Pippin, did you ever get this sorted out? If so, it would be great to post your answer/findings here for others. Thanks! Feb 7 '12 at 23:21
  • No, a solution was never found.
    – Pippin
    Feb 8 '12 at 2:50
1

That sounds pretty simple.

Use: http://codex.wordpress.org/Function_Reference/switch_to_blog

To go back use:

restore_current_blog();

This allows you to switch from site to site.

Then: http://codex.wordpress.org/Function_Reference/get_permalink

My assumptions are that you have both the Blog ID and the Post ID.

If that's the case - using those two functions should solve your problem.

4
  • switch_to_blog() documentation states that this function is a performance hog and should not be used in frontend functions.
    – Ejaz
    Oct 7 '15 at 8:07
  • I'm not seeing that for what it's worth. Jan 20 '16 at 0:38
  • I meant "This switch is to be used for internal and admin area functions. It's too expensive a query to run on the front end." part on codex.wordpress.org/WPMU_Functions/switch_to_blog. I could be misunderstanding your comment?
    – Ejaz
    Jan 20 '16 at 2:00
  • Ah yes. You're correct. It might be an option to attache this work to a cron -- have it generate a cached list of all the blog sensitive related data you needed. That's a little lame hack though. Jan 20 '16 at 2:37
0

As per the suggestion above, I've gone for this:

$html = '<ul>';
foreach ( $recent_across_network as $post ) {

    switch_to_blog( $post->blog_id );

    $postURI = get_permalink( $post->ID );          
    $html .= '<li><a href="' . $postURI . '">' . $post->post_title . '</a></li>';

    restore_current_blog();
}
$html .= '</ul>';

where $recent_across_network is a list of recent posts from across a multisite network, cached using the Transients API. There's a related tutorial here.

You could equally do:

$postURI = get_blog_permalink( $post->blog_id, $post->ID );

instead of switch_to_blog() / restore_current_blog() - not sure which is more efficient?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.