I am trying to add the featured image to posts and that works, however, the featured image is apparently set everytime I check my post.
<?php
$post_id = get_queried_object_id();
$bla = "myImageURL";
// Set the image URL
$image_url = $bla;
// Download the image
$image_id = media_sideload_image($image_url, $post_id, '', 'id');
// Check for errors
if (is_wp_error($image_id)) {
print_r($image_url);
} else {
// The image was downloaded successfully. Now set it as the featured image for the post
set_post_thumbnail($post_id, $image_id);
}
?>
So, every time I view my post, it adds the featured image AGAIN to my media library.
How can I prevent that from happening?
I tried:
elseif (!has_post_thumbnail($post_id)) {
set_post_thumbnail($post_id, $image_id);
}
But sadly this did not work either. The below also did not work (based on answer here below):
<?php
$post_id = get_queried_object_id();
$bla = MyIMGURL;
// Set the image URL
$image_url = $bla;
'attachment', 'meta_key' => '_wp_attached_file', 'meta_value' => sanitize_file_name(basename($image_url)); if (!$existing_image) { // Image does not exist in the media library, so download it
$image_id = media_sideload_image($image_url, $post_id, '', 'id'); // Check for errors
if (is_wp_error($image_id)) { print_r($image_url); } else { // The image was downloaded successfully.
?>