Resizing images in WordPress using url

I need to resize some images in some of my posts. I can get the url of the image stored in postmeta generated with the Plugin Type .
So using postmeta I can get the url, but how do I resize images of a specific post type?

+3


source to share


1 answer


You must first find the attached image id from the image url. To get the attached image id from the image url, add the function below to the theme functions.php

:

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 see url - https://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/

Then we need to use the image resizing function in function.php

:

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

      



To use an image attachment ID:

$attachid = pn_get_attachment_id_from_url($url);

      

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

After that use this to get the regenerated image url:

$src = wp_get_attachment_image_src($attachid, 'latestproperty_thumb');

      

+4


source







All Articles