I got the image src from user input by a metabox field. Now I want to render this image in a specific size. Just as like WordPress image cropping in a specific size.
I tried to get the image ID from the src then used the bellow function to get the image src with a sized image.
<?php
$img_id = get_image_id($img_src);
$sized_img_src = wp_get_attachment_image_src($img_id, 'image_size');
And here is the get_image_id()
function:
function get_image_id($image_url) {
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
return $attachment[0];
}
Actually, I’m not getting the image IDs for uploaded images with this function. Where is the problem?
WordPress has a function solely designed for this purpose. the attachment_url_to_postid()
allows you to retrieve an attachment’s ID from it’s URL, which then you can use to get the post’s ID later.
If you want to do it by writing a MySQL query, i would however prefer to suggest searching the file’s name in meta_value
instead:
$basename = basename ($image_url);
$sql = "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value="$basename "";
$id = $wpdb->get_var($sql);
GUID columns are hardcoded in database once you publish a post. So, if you publish a post on localhost, a sample GUID will be like this:
http://localhost/wp-content/uploads/my-image.jpg
But you will be searching for an online URL of your image by using this:
$wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
Which will return nothing, obviously. However you can use LIKE
in conjunction with basename:
$img_name = basename ($image_url);
$wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid LIKE '%s';", $img_name ));
Which is kind of the same as the first approach.