2

we are having a multisite Wordpress site, where we sync some external data with given image from ftp directory as featured image. On site 1 this process works like a charme. but on all the other sites, the wp_insert_attachment function is missing something. we get a attachment-id and we can see rising amount of posts @ database and can“t find a difference between manual und programmatically generated images but: in the media library of wordpress the picture is actually missing but present in the upload directory of the multisite (for example /wp-content/uploads/sites/2/2021/05)

here is how we insert the attachment:

require_once("wp-load.php");
require_once(ABSPATH . 'wp-admin/includes/image.php');    

switch_to_blog(2);
$IMGFileName = 'filename123.jpg';
$IMGFilePath = ABSPATH. 'path/to/files/'.$IMGFileName;

// Add Featured Image to Post
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($IMGFilePath); // Get image data
$filename   = basename($IMGFilePath); // Create image file name

// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
    $file = $upload_dir['path'] . '/' . $filename;
} else {
    $file = $upload_dir['basedir'] . '/' . $filename;
}

// Create the image  file on the server
file_put_contents( $file, $image_data );

// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );

// Set attachment data
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => '',
    'post_status'    => 'inherit'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file );

// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');

// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );

// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );

It seems like the switch_to_blog(2); is ignored in some of the functions. Do someone know, what we are missing here?

Luco
  • 21
  • 1

1 Answers1

0

Not a solution but this might give a clue. We hade a similar issue related to media-upload and the "insert into post" button. It worked fine on site 1 of our multisite setup but not on any other sites added after that.

After a lot of digging I realised that on site 1 (and on normal single sites) the "insert into post" returns the img element wrapped in an anchor tag, e.g '<a href="#"><img src="url"></a>'.

Whereas on site 2 and following sites on a multisite the "insert into post" button only returns the img element, i.e '<img src="url">'.

In our case the jQuery used to get the src attribute assumed the img element was wrapped in another element, that's why it did not work for us.

This might not be related at all to your issue but I found your question while searching for our issue, so it might help others.