Skip to content

Instantly share code, notes, and snippets.

@svenl77
Last active October 30, 2016 08:31
Show Gist options
  • Save svenl77/e13ef7b02dccb089d0a70213146d5698 to your computer and use it in GitHub Desktop.
Save svenl77/e13ef7b02dccb089d0a70213146d5698 to your computer and use it in GitHub Desktop.
Copy a featured image from current site to blog in the network
<?php
// Let us make sure we are on the curent site.
restore_current_blog();
// get the image src
$image_url = wp_get_attachment_image_src( $_POST['featured_image'], 'full' );
$image_url = $image_url[0];
// Now let us switch to the Blog we like to set the featured image
switch_to_blog( $buddyforms[ $form_slug ]['blog_id'] );
// Add Featured Image to Post
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents( $image_url ); // Get image data
$filename = basename( $image_url ); // 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, $post_id );
// 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 );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment