Created
September 15, 2023 01:33
-
-
Save crazyyy/5855a5b1fb75ae40d1d52f00c3dc9e44 to your computer and use it in GitHub Desktop.
This plugin automatically sets the first embedded image as the featured image for new posts that do not have a specified featured image.
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 | |
/** | |
* Sets the first embedded image as the featured image for a post. | |
* | |
* @since 1.0.0 | |
* | |
* @param int $post_id The ID of the post. | |
*/ | |
function auto_set_featured($post_id) { | |
// Get the post object | |
$post = get_post($post_id); | |
// Get out if this isn't a post or if the post already has a thumbnail | |
if (!$post instanceof WP_Post || has_post_thumbnail($post_id)) { | |
return; | |
} | |
// Get the first embedded image | |
$images = get_posts(array( | |
'post_parent' => $post_id, | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'post_mime_type' => 'image', | |
'posts_per_page' => 1 | |
)); | |
// Set the first image as the post thumbnail if it's not already set for another post | |
if (!empty($images)) { | |
$thumbnail = reset($images); | |
$thumbnail_post_id = get_post_thumbnail_id($thumbnail->ID); | |
if (empty($thumbnail_post_id)) { | |
set_post_thumbnail($post_id, $thumbnail->ID); | |
} | |
} | |
} | |
// Run the auto_set_featured function when a post is published | |
add_action('publish_post', 'auto_set_featured'); | |
/** | |
* Runs the auto_set_featured function to set the first image as the featured image for older posts without a featured image. | |
* | |
* @since 1.0.0 | |
*/ | |
add_action('admin_init', function () { | |
// Check if the transient exists | |
if ((int)get_transient('bulk_auto_set_featured') > 0) { | |
return; | |
} | |
// Get all posts | |
$posts = get_posts(array( | |
'posts_per_page' => -1, | |
)); | |
// Set the featured image for each post without a featured image | |
if (!empty($posts)) { | |
array_walk($posts, 'auto_set_featured'); | |
} | |
// Set the transient to indicate that the function has been run | |
set_transient('bulk_auto_set_featured', 1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment