add_action( 'wp_footer', 'set_post_thumbnail_post_type_projects' ); function set_post_thumbnail_post_type_projects(){ $args = array( 'posts_per_page' => -1, 'post_type' => 'projects', ); $query = new WP_Query( $args ); if( $query->have_posts() && is_user_logged_in() ){ while ( $query->have_posts() ) { $query->the_post(); $content = get_the_content(); $post_id = get_the_ID(); if ( preg_match_all( '/<img [^>]+>/', $content, $matches ) ) { foreach ( (array) $matches[0] as $image ) { if ( ! preg_match( '/src="([^"]+)"/', $image, $url_matches ) ) { continue; } $image_src = $url_matches[1]; // Don't try to sideload a file without a file extension, leads to WP upload error. if ( ! preg_match( '/[^\?]+\.(?:jpe?g|jpe|gif|png)(?:\?|$)/i', $image_src ) ) { continue; } $image_path = site_url().'/wp-content/uploads/'; $image_attached_file = str_replace( $image_path, '', $image_src); if( !has_post_thumbnail( $post_id ) ){ $thumbnail_id = getIDfromGUID( $image_attached_file ); set_post_thumbnail( $post_id, $thumbnail_id ); break; } } } } wp_reset_postdata(); } }