Created
February 19, 2023 18:03
-
-
Save wipermail/f8cf1a8c2296051f1d0412c5d4d958b2 to your computer and use it in GitHub Desktop.
Wordpress. Save Image With PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function houzez_property_img_upload_houzi_import( $img_url ): array { | |
$upload_dir = wp_upload_dir(); | |
$image_data = file_get_contents( $img_url ); | |
$filename = basename( $img_url ); | |
if ( wp_mkdir_p( $upload_dir['path'] ) ) { | |
$file = $upload_dir['path'] . '/' . $filename; | |
} | |
else { | |
$file = $upload_dir['basedir'] . '/' . $filename; | |
} | |
file_put_contents( $file, $image_data ); | |
$wp_filetype = wp_check_filetype( $filename ); | |
$attachment = array( | |
'guid' => $img_url, | |
'post_mime_type' => $wp_filetype['type'], | |
'post_title' => preg_replace( '/\.[^.]+$/', '',sanitize_file_name( $filename )), | |
'post_content' => '', | |
'post_status' => 'inherit' | |
); | |
$attach_id = wp_insert_attachment( $attachment, $file ); | |
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 ); | |
$thumbnail_url = wp_get_attachment_image_src( $attach_id, 'houzez-item-image-1' ); | |
$feat_image_url = wp_get_attachment_url( $attach_id ); | |
return array( | |
'success' => true, | |
'url' => $thumbnail_url[0], | |
'attachment_id' => $attach_id, | |
'full_image' => $feat_image_url | |
); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment