From f824ab488c07eafeaf26b763dad83779a2a7581a Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Sun, 21 May 2023 12:34:05 +0200 Subject: Set post thumbnail from custom teaser if present. --- import-posts.php | 88 +++++++++++++++++++++++++++++--------------------------- 1 file changed, 45 insertions(+), 43 deletions(-) (limited to 'import-posts.php') diff --git a/import-posts.php b/import-posts.php index 70aa7a4..9c872c0 100644 --- a/import-posts.php +++ b/import-posts.php @@ -137,49 +137,51 @@ function migrate_images( array $meta ) : array { $thumb = null; - if ( isset( $meta['body'] ) ) { - $body = preg_replace_callback( - '/([^]*>/', - function( array $matches ) use ( $post_date, &$thumb ) { - $remote_filename = get_real_image_name( $matches[1] ); - $filename = basename( $remote_filename ); - $title = $matches[2]; - $alt = $matches[3]; - - $uploads = wp_upload_dir( $post_date->format( 'Y/m' ) ); - $target_file = implode( '/', array( $uploads['path'], $filename ) ); - $target_url = implode( '/', array( $uploads['url'], $filename ) ); - - import_photo( $remote_filename, $target_file ); - - $mime = wp_get_image_mime( $target_file ); - if ( ! $mime ) { - die( "Error: Unknown mime type for {$target_file}" . PHP_EOL ); - } - - $attachment_id = wp_insert_attachment( - array( - 'post_mime_type' => $mime, - 'guid' => $target_url, - 'post_paren' => 0, - 'post_title' => $filename, - ), - $target_file - ); - - if ( 0 === $attachment_id ) { - die( "Error: Could not create attachment for {$target_file}" . PHP_EOL ); - } - - if ( null === $thumb ) { - $thumb = $attachment_id; - return ''; - } else { - return "\"{$alt}\""; - } - }, - $meta['body'], - ); + foreach ( array( 'custom_teaser', 'body' ) as $section ) { + if ( isset( $meta[$section] ) ) { + $body = preg_replace_callback( + '/([^]*>/', + function( array $matches ) use ( $post_date, &$thumb ) { + $remote_filename = get_real_image_name( $matches[1] ); + $filename = basename( $remote_filename ); + $title = $matches[2]; + $alt = $matches[3]; + + $uploads = wp_upload_dir( $post_date->format( 'Y/m' ) ); + $target_file = implode( '/', array( $uploads['path'], $filename ) ); + $target_url = implode( '/', array( $uploads['url'], $filename ) ); + + import_photo( $remote_filename, $target_file ); + + $mime = wp_get_image_mime( $target_file ); + if ( ! $mime ) { + die( "Error: Unknown mime type for {$target_file}" . PHP_EOL ); + } + + $attachment_id = wp_insert_attachment( + array( + 'post_mime_type' => $mime, + 'guid' => $target_url, + 'post_paren' => 0, + 'post_title' => $filename, + ), + $target_file + ); + + if ( 0 === $attachment_id ) { + die( "Error: Could not create attachment for {$target_file}" . PHP_EOL ); + } + + if ( null === $thumb ) { + $thumb = $attachment_id; + return ''; + } else { + return "\"{$alt}\""; + } + }, + $meta[$section], + ); + } } return array( $body, $thumb ); -- cgit v1.2.3