Reputation: 1591
I want to set featured images for different posts on WordPress website if the images are already uploaded on the server.
I plan on using the following code to do so:
// File has already been uploaded
$image_url = 'path/of/image';
if(file_exists($image_url)) {
set_post_thumbnail($post_id, $image_id);
}
The problem is that I cannot figure out how to get the $image_id
from just the image URL and nothing else. Is it possible in WordPress?
I would just like to clarify again that the image is already in the media library.
I have read this question: https://wordpress.stackexchange.com/questions/40301/how-do-i-set-a-featured-image-thumbnail-by-image-url-when-using-wp-insert-post but it does not tell me how to get the id
of an image that is already in the media library.
I need something that is opposite of wp_get_attachment_url($id)
. This function returns the image path based on its id.
I want to get the image id based on its path or URL.
Thanks.
Upvotes: 0
Views: 1440
Reputation: 1502
Please Use the below code :
$image_url = 'path/of/image';
if(file_exists($image_url)) {
global $wpdb;
$table_name = $wpdb->prefix . "posts";
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $table_name WHERE guid='%s';", $image_url ));
$image_id = $attachment[0];
set_post_thumbnail($post_id, $image_id);
}
I hope it will help you.
Upvotes: 2
Reputation: 2621
Try the following.
post.php?post=1234&action=edit
See the value post=1234
part of url, 1234
is the image id. Please try with this and let me know if it works.
Upvotes: 0