Last active
January 18, 2023 22:25
-
-
Save brandonjp/ceb8ed680795d872d94d33a5cee1c021 to your computer and use it in GitHub Desktop.
Posts: Auto Set First Image as Featured - WP / Code Snippets Pro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // <- remove this line if you copy/paste into Code Snippets Pro | |
/** | |
* Posts: Auto Set First Image as Featured | |
* | |
* Takes the first image attached to a post and sets it as the post's featured image. | |
* | |
* Code from: https://wordpress.stackexchange.com/a/131436 | |
*/ | |
namespace xKceqd2; | |
// from: https://wordpress.stackexchange.com/a/131436 | |
function auto_set_featured($post = NULL) | |
{ | |
// retrieve post object | |
$post = get_post($post); | |
// nothing to do if no post, or post already has thumbnail | |
if (!$post instanceof \WP_Post || has_post_thumbnail($post->ID)) | |
return; | |
// prepare $thumbnail var | |
$thumbnail = NULL; | |
$args = array( | |
'post_parent' => $post->ID, | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'post_mime_type' => 'image', | |
'order' => 'ASC', | |
'numberposts' => 1, | |
'posts_per_page' => 1 | |
); | |
// retrieve all the images uploaded to the post | |
$images = get_posts($args); | |
// if we got some images, save the first in $thumbnail var | |
if (is_array($images) && !empty($images)) | |
$thumbnail = reset($images); | |
// if $thumbnail var is valid, set as featured for the post | |
if ($thumbnail instanceof \WP_Post) | |
set_post_thumbnail($post->ID, $thumbnail->ID); | |
} | |
add_action('save_post', '\xKceqd2\auto_set_featured'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PHP snippet for Code Snippets Pro
Posts: Auto Set First Image as Featured
Takes the first image attached to a post and sets it as the post's featured image.
Code from: https://wordpress.stackexchange.com/a/131436