Monday, October 30, 2017

Resize images in WordPress using its URL

Leave a Comment

I need to resize some images in some of my posts. I can get the image URL stored in postmeta created using the Types plugin.
So using postmeta I can get the URL, but how to resize the images of a specific post type?

1 Answers

Answers 1

First you have to find attached image id from image URL. To get attached image id from image URL add below function in your theme functions.php file:

function pn_get_attachment_id_from_url( $attachment_url = '' ) {     global $wpdb;      $attachment_id = false;      // If there is no url, return.     if ('' == $attachment_url)         return;      // Get the upload directory paths     $upload_dir_paths = wp_upload_dir();      // Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image     if (false !== strpos($attachment_url, $upload_dir_paths['baseurl'])) {          // If this is the URL of an auto-generated thumbnail, get the URL of the original image         $attachment_url = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url);          // Remove the upload path base directory from the attachment URL         $attachment_url = str_replace($upload_dir_paths['baseurl'] . '/', '', $attachment_url);          // Finally, run a custom database query to get the attachment ID from the modified attachment URL         $attachment_id = $wpdb->get_var($wpdb->prepare("SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url));     }      return $attachment_id; } 

For more information read see url - https://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/

Then we need to use image resize function in function.php:

add_image_size( 'latestproperty_thumb', 370,293,true ); 

To get the image attachment id use:

$attachid = pn_get_attachment_id_from_url($url); 

After this install https://wordpress.org/plugins/regenerate-thumbnails/. Then go to Tools->Regenerate thumbnail and regenerate all thumbnails.

After that use this to get the regenerated image url:

$src = wp_get_attachment_image_src($attachid, 'latestproperty_thumb'); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment