Get attachment or image id by url – WordPress
Today I will talk about one non-standard task that WordPress can't do by default., namely, to take from the database the ID of the picture (or other investment) by her URL. Such a task is often necessary when developing plugins or new WordPress themes..
First we need a function that will make a request to the database and get the required image by URL.
1 2 3 4 5 6 |
// возвращает ID картинки по URL function pippin_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]; } |
This function can be put in the functions.php file and called anywhere in the template.
How to call a function to pass a URL and return an image ID
Below I will show which will pass the URL of the image to the rename and get the ID of the attachment, also below is the code with which you can resize the image using the standard WordPress function wp_get_attachment_image_src().
1 2 3 4 5 6 7 8 9 10 11 |
// передаем в переменную url картинки на вашем сайте $image_url = 'https://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg'; // получаем ID картинки по URL из переменной $image_url $image_id = pippin_get_image_id($image_url); // Получаем ту же картинку по ID но с новым размером $image_thumb = wp_get_attachment_image_src($image_id, 'thumbnail'); // выводим картинку с новым размером на экран echo $image_thumb[0]; |
I would like to say that this should not be abused, because the task is not completed very quickly.
/*
- Basic web design course;
- Site layout;
- General course on CMS WordPress and continuation of the course on template development;
- Website development in PHP.