Featured Images from the Original Site

By default my plugin uses original image files in post content but it copies featured images to sub-sites. It was made with the performance in mind, because it is much easier to copy an image just one time and then to use it as usual, than doing some tricks and dances with hooks and switch_to_blog() functions on every page load.

Anyways, sometimes you just need that and I will show you how to accomplish it in two simple steps.

1. Turn off image copying in my plugin

You can do it with this filter hook.

add_filter( 'rudr_crosspost_ignore_images', '__return_true' );

2. Hook the standard WordPress function that gets the image

The function I am talking about here is wp_get_attachment_image_src(). Some examples of filtering it you can find in this tutorial.

add_filter( 'wp_get_attachment_image_src', 'rudr_get_thumbnail', 10, 4 );

function rudr_get_thumbnail( $image, $attachment_id, $size, $icon ) {
	
	// check if it is actually a post thumbnail of a current post
	if( $attachment_id !== get_the_ID() ) {
		return $image;	
	}
	
	// what is the ID of original blog, you can use _source_blog_id meta key
	$source_blog_id = get_post_meta( get_the_ID(), '_source_blog_id', true );
	
	if( $source_blog_id === get_current_blog_id() ) {
		return $image;
	}

	remove_filter( 'wp_get_attachment_image_src', 'rudr_get_thumbnail', 10, 4 );
	switch_to_blog( $source_blog_id );
	$image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
	add_filter( 'wp_get_attachment_image_src', 'rudr_get_thumbnail', 10, 4 );
	restore_current_blog();

	return $image;

}

Need more help?