Attachments in custom fields

Let’s imagine a situation when you have a custom field where you can upload an image or file. And the custom field doesn’t store a file URL, but its ID. What should we do in this case, because on subsites, where we about to crosspost to, the file may not exist or even if it exists, its ID most likely will be different.

If you’re using ACF, you just need to install and activate an add-on from here.

But what to do if your custom fields aren’t created with ACF? Maybe they are created with any other custom fields plugin or maybe even coded directly in your theme.

  1. First of all, let’s decide under what meta keys our attachment IDs are stored in the database. Let’s say the keys are my_image_field and post_bg_image_blah_blah.
  2. The second step – just copy and paste an appropriate code snippet from below depending on which plugin you’re using (either Simple Multisite Crossposting or Simple WP Crossposting).

For Simple WP Crossposting:

add_filter( 'rudr_swc_pre_crosspost_meta', 'rudr_process_attachment_meta', 10, 4 );
function rudr_process_attachment_meta( $value, $key, $object_id, $blog ) {
	
	// list of meta keys with attachment IDs
	$attachment_keys = array(
		'my_image_field',
		'post_bg_image_blah_blah',
	);
	// not an attachment meta key
	if( ! in_array( $key, $attachment_keys ) ) {
		return $value;
	}
	// try to get an attachment ID from $blog, copy it if necessary
	$crossposted = Rudr_Simple_WP_Crosspost::maybe_crosspost_image( $value, $blog );

	return isset( $crossposted[ 'id' ] ) ? $crossposted[ 'id' ] : $value;
	
}

For Simple Multisite Crossposting:

add_filter( 'rudr_pre_crosspost_meta', 'rudr_process_attachment_meta', 10, 3 );
function rudr_process_attachment_meta( $value, $key, $object_id ) {
	
	// list of meta keys with attachment IDs
	$attachment_keys = array(
		'my_image_field',
		'post_bg_image_blah_blah',
	);
	// not an attachment meta key
	if( ! in_array( $key, $attachment_keys ) ) {
		return $value;
	}
	
	$new_blog_id = get_current_blog_id();
	
	// let's switch to a previous blog to get all the attachment metadata
	restore_current_blog();
	$attachment = Rudr_Simple_Multisite_Crosspost::prepare_attachment_data( $value );
	
	// get back to the current blog and try to copy an image
	switch_to_blog( $new_blog_id );
	$crossposted = Rudr_Simple_Multisite_Crosspost::maybe_copy_image( $attachment );
	
	return isset( $crossposted[ 'id' ] ) ? $crossposted[ 'id' ] : $value;
	
}

In both cases the snippets should be inserted to “Site 1” – the site you’re about to crosspost from. In case you don’t know how – please read this.

Just to double check, after using the snippets above:

  1. Attachment (or attachments) are going to be copied to sub-sites if necessary.
  2. The meta values will be replaced with the appropriate attachment IDs on sub-sites.

Need more help?