Wednesday, August 28, 2019

Save image from url to disk and crop it in wordpress

Save image from url to disk and crop it in wordpress:
Follow the below code block to achieve this

$upload_dir = wp_upload_dir();

$file_name = explode('/', $first_image['src']); /* put your image url in this variable $first_image['src'] */
$file_name = end($file_name);

$data = file_get_contents($first_image['src']);

$new_image = $upload_dir['basedir'] .'/'. $file_name;
file_put_contents($new_image, $data);

$image_size = '320x190';
$img_temp = explode("x", $image_size);
$img_width = $img_temp[0];
$img_height = $img_temp[1];

$image = wp_get_image_editor( $new_image );
if ( ! is_wp_error( $image ) ) {
  $image->resize( $img_width, $img_height, true );
  $image->save( $new_image );
}


$output .= '<div class="wp_rss_retriever_image"><img' . $class . ' src="' . $upload_dir['baseurl'] . '/' . $file_name . '" alt="' . $title . '"></div>';

.:Happy Coding:.

No comments:

Post a Comment

Suomen kieli (Imperfekti)

In Finnish, the imperfekti is the past tense that describes actions that happened in the past, like the English simple past (e.g., "I ...