{"id":55,"date":"2024-02-29T19:47:02","date_gmt":"2024-02-29T19:47:02","guid":{"rendered":"https:\/\/www.kwwd.co.uk\/blog\/?p=55"},"modified":"2024-02-29T19:48:40","modified_gmt":"2024-02-29T19:48:40","slug":"set-first-image-in-wordpress-post-as-the-featured-image","status":"publish","type":"post","link":"https:\/\/www.kwwd.co.uk\/blog\/set-first-image-in-wordpress-post-as-the-featured-image\/","title":{"rendered":"Set First Image In WordPress Post As The Featured Image"},"content":{"rendered":"<p>Add the following code to your functions.php file.<\/p>\n<p>To run it, simply visit any page on the site &#8211; DO NOT USE THIS CODE ON YOUR LIVE SITE! Any visitor that visits any page will trigger this code. This code was created to manipulate content on a development site before it was merged with the live site<\/p>\n<pre><code class=\"language-php line-numbers\">\r\n\r\n\/** Function to set the first image as featured **\/\r\nfunction set_first_image_as_featured() \r\n{\r\n\/** Set the post arguments, here we're targetting all posts in the\r\n\tTo go through all posts \r\n**\/\r\n  $args = array(\r\n    'post_type' =&gt; 'post',\r\n\t'category_name' =&gt; 'articles',\r\n    'numberposts' =&gt; -1, \/\/ Modify this to limit the number of posts if needed\r\n  );\r\n\r\n  $posts = get_posts($args);\r\n\r\n\/** Force include image files so that we can download and\r\n    save the images locally  \r\n**\/\r\nif(!function_exists('wp_get_current_user')) {\r\ninclude(ABSPATH . \"wp-includes\/pluggable.php\"); \r\n}\r\nrequire_once(ABSPATH . 'wp-admin\/includes\/media.php');\r\nrequire_once(ABSPATH . 'wp-admin\/includes\/file.php');\r\nrequire_once(ABSPATH . 'wp-admin\/includes\/image.php');\r\n\r\n\/** Loop through all posts **\/\r\n\r\n  foreach ($posts as $post) {\r\n  \/** Only run if we don't already have a thmbnail image set **\/\r\n if (!has_post_thumbnail($post-&gt;ID)) \r\n { \r\n\r\n    $content = get_post_field('post_content', $post-&gt;ID);\r\n\t$alttext = get_post_field('post_title', $post-&gt;ID);\r\n\t\/** Check we have post content to check **\/\r\n\tif($content!='')\r\n\t{\r\n\t\r\n\t$doc = new DOMDocument();\r\n    @$doc-&gt;loadHTML($content);\r\n\t\/** Grab All Image Elements in the DOM. You can change 'img' to any\r\n\t    HTML tag such as 'p', 'iframe' etc - amend the following code\r\n             according to your needs\r\n\t**\/\r\n    $images = $doc-&gt;getElementsByTagName('img');\r\n\t\r\n\t\/** Check to make sure we have at least one image in the post **\/\r\n    if ($images-&gt;length &gt; 0) \r\n\t{\r\n\t\t\/** Get the URL of the first image **\/\r\n      $first_image_url = $images-&gt;item(0)-&gt;getAttribute('src');\r\n\t  \r\n     \/** Check if image URL starts with an external domain (not your own website)**\/\r\n     if (strpos($first_image_url, get_home_url()) === false) {\r\n\t\t\r\n        \/** WARNING: Downloading from external sources can have copyright and security risks.**\/\r\n\t\t\r\n\t\t\/** Add the image to the WordPress Media Library and grab the id of the insered image\r\n\t\t    So we can assign it as the post thumbnail later\r\n\t\t**\/\r\n        $featured_image_id = media_sideload_image($first_image_url, $post-&gt;ID, $alttext, 'id');\r\n\t   \r\n\t\t\/** Check whether we have a valid image id so we can attach it to the post **\/\r\n        if (!is_wp_error($featured_image_id)) \r\n\t\t{\r\n\t\t\t\/** Set the post thumbnail with the first image in the post **\/\r\n\t\t\tset_post_thumbnail($post-&gt;ID, $featured_image_id);\r\n\t\t\t\r\n\t\t\t\/** Remove the image from the post content and save the amended content\r\n\t\t\t\tComment Out the line below if you want to keep the image in the post\r\n\t\t\t**\/\r\n\t\t\tupdate_post_content_with_image_removed($post-&gt;ID, $first_image_url);\r\n\t\t\t\r\n\t\t\t\/** Uncomment the following line for visual confirmation of items updated **\/\r\n\t\t\t\/\/echo 'done '.$post-&gt;ID.' IMG ID '.$featured_image_id. ' IMG - '.$first_image_url.' ALT - '.$alttext.'&lt;br&gt;';\r\n        } \/\/ End Set post thumb\r\n\t\t\r\n      } \/\/ END External Image Check\r\n    } \/\/ END Has in post image\r\n  }\/\/ End has Content\r\n}\/\/ END Has Thumbnail\r\n} \/\/ END Post Loop\r\n\r\n} \/\/ End function\r\n\r\n\/** Run the function after WordPress is loaded **\/\r\nadd_action('init', 'set_first_image_as_featured');\r\n\r\nfunction update_post_content_with_image_removed($post_id, $image_url) \r\n{\r\n  \/\/ 1. Fetch the existing post content\r\n  $existing_content = get_post_field('post_content', $post_id);\r\n\r\n  \/\/ 2. Escape the image URL for safe use in string replacement\r\n  $escaped_url = str_replace('\/', '\\\\\/', $image_url);\r\n\r\n  \/\/ 3. Remove the '&lt;img&gt;' tag with the specified URL using regular expressions\r\n  \/\/ This approach is more flexible than str_replace for potential variations in the tag\r\n  $updated_content = preg_replace('\/&lt;img[^&gt;]*?src=\"' . $escaped_url . '\"[^&gt;]*?&gt;\/i', '', $existing_content);\r\n  \r\n  \/\/ 4. Update the post content in the database\r\n  $args = array(\r\n    'ID' =&gt; $post_id,\r\n    'post_content' =&gt; $updated_content,\r\n  );\r\n\r\n\t\/\/ Update the post with the revised content\r\n\t\twp_update_post($args);\r\n  \r\n} \/\/ END update_post_content_with_image_removed\r\n\r\n<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Add the following code to your functions.php file. To run it, simply visit any page on the site &#8211; DO NOT USE THIS CODE ON [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[28,26,9,27,12],"class_list":["post-55","post","type-post","status-publish","format-standard","hentry","category-wordpress","tag-dom","tag-images","tag-php","tag-post-content","tag-wordpress"],"_links":{"self":[{"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/posts\/55","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/comments?post=55"}],"version-history":[{"count":0,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/posts\/55\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/media?parent=55"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/categories?post=55"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kwwd.co.uk\/blog\/wp-json\/wp\/v2\/tags?post=55"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}