Friday, 16 August 2013

Code to make other site image to get stored in your wordpress database as well as making other site images to your wordpress post featured image

$upload_dir = wp_upload_dir();
$image_data = file_get_contents("Image URL for other site");
$filename = basename($image_url);
$file = $upload_dir['path'] . '/' . $filename;
$file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);

$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id , $attach_id );

wp_update_attachment_metadata will make the image to get stored in your database

set_post_thumbnail will make the image to get featured for the post

$post_id - will be ID of your post, for example if you just want to make your post id 5 to get featured image then just replace the variable  $post_id with 5

No comments:

Post a comment