/**
* Set the first image in the post content as Featured Image.
*/
add_action( 'save_post', function( $post_id, $post = NULL ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !isset( $_REQUEST[ 'post_type' ] ) || $_REQUEST[ 'post_type' ] != 'post' )
return;
tsg_set_featured_image( $post );
}, 10, 2 );
add_action( 'transition_post_status', function( $new_status, $old_status, $post ) {
if ( $post->post_type != 'post' )
return;
tsg_set_featured_image( $post );
}, 10, 3 );
function tsg_set_featured_image( $post )
{
if ( $post->post_type != 'post' )
return;
if ( has_post_thumbnail( $post ) )
return;
$attachment_id = tsg_get_first_attachment_id( $post );
if ( !empty( $attachment_id ) )
update_post_meta( $post->ID, '_thumbnail_id', $attachment_id );
}
/**
* Get attachment ID from image url.
*/
function tsg_get_first_attachment_id( $post )
{
$image_url = tsg_get_first_image_from_post_content( $post );
if ( empty( $image_url ) )
return;
$image_extension = explode( '.', $image_url );
$image_extension = end( $image_extension );
if ( !in_array( $image_extension , [ 'png', 'PNG', 'jpg', 'JPG', 'jpeg', 'JPEG' ] ) )
return;
$image_url = parse_url( $image_url );
// Uncomment and add your domain if you only want the database lookup to occur for your domain.
// if ( strpos( $image_url[ 'host' ], 'yourdomain.com' ) === false )
// return;
$image_path = preg_replace( '/-\d+[Xx]\d+\.' . $image_extension . '/', '.' . $image_extension, $image_url[ 'path' ] );
$attachment_id = tsg_get_post_id_by_guid( $image_path );
return $attachment_id;
}
/**
* Get the first image from the post content.
*/
function tsg_get_first_image_from_post_content( $post )
{
if ( empty( $post->post_content ) )
return;
$content = apply_filters( 'the_content', $post->post_content );
preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches );
if ( empty( $matches[ 1 ] ) )
return;
return $matches[ 1 ][ 0 ];
}
/**
* Get post ID by guid.
*/
function tsg_get_post_id_by_guid( $guid )
{
global $wpdb;
$post_id = $wpdb->get_col(
$wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE instr( guid, '%s' ) > 0", $guid )
);
if ( !empty( $post_id[ 0 ] ) )
return $post_id[ 0 ];
else
return;
}
/**
* Describe the new functionality on the Featured Image metabox.
*/
add_action( 'admin_footer-post-new.php', 'tsg_featured_image_notice' );
add_action( 'admin_footer-post.php', 'tsg_featured_image_notice' );
function tsg_featured_image_notice()
{
global $current_screen;
if ( $current_screen->post_type != 'post' )
return;
?>
<script type="text/javascript">
jQuery( '#set-post-thumbnail-desc' ).after( '<p class="hide-if-no-js howto" id="set-post-thumbnail-desc1">The first image in your post is set automatically as the featured image, however, you are able to select an alternate image</p>' );
</script>
<?php
}