Created
July 9, 2018 14:46
-
-
Save bdeleasa/1a3acde2b879fc922d9e689bf17f31fd to your computer and use it in GitHub Desktop.
Makes sure all posts have a featured image. Updates older posts and sets the first embedded image as the featured image. Also does the same for any new posts created.
This file contains 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 | |
/** | |
* Plugin Name: Fix Featured Images | |
* Description: Makes sure all posts have a featured image. Updates older posts and sets the first embedded image as the featured image. Also does the same for any new posts created. | |
* Plugin URI: http://briannadeleasa.com | |
* Version: 0.1.0 | |
* Author: Brianna Deleasa | |
* Author URI: http://briannadeleasa.com | |
* Text Domain: fix-featured-images | |
*/ | |
add_action( 'save_post', 'auto_set_featured' ); | |
/** | |
* When new posts are saved, if the user didn't specify a featured image, | |
* this will pull the first embedded image and set it as the featured image. | |
* | |
* @since 1.0.0 | |
* | |
* @param null $post | |
* @return null | |
*/ | |
function auto_set_featured( $post = NULL ) { | |
$post = get_post( $post ); | |
// 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; | |
$thumbnail = NULL; | |
$images = get_posts( array( | |
'post_parent' => $post->ID, | |
'post_type' => 'attachment', | |
'post_status' => 'inherit', | |
'post_mime_type' => 'image', | |
'posts_per_page' => 1 | |
) ); | |
// Get the first image and set it as the post thumbnail | |
if ( is_array( $images ) && ! empty( $images ) ) | |
$thumbnail = reset( $images ); | |
if ( $thumbnail instanceof WP_Post ) | |
set_post_thumbnail( $post->ID, $thumbnail->ID ); | |
} | |
/** | |
* This is meant to only run once on older posts. It runs the function above | |
* to set the first image as the featured image for posts without a featured | |
* image. | |
* | |
* @since 1.0.0 | |
*/ | |
add_action( 'admin_init', function() { | |
if ( (int) get_transient( 'bulk_auto_set_featured' ) > 0 ) | |
return; | |
$posts = get_posts( 'posts_per_page=-1' ) ; | |
if ( empty( $posts ) ) | |
return; | |
array_walk( $posts, 'auto_set_featured' ); | |
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