基于对相关问题的公认答案,我认为类似的方法可能会奏效。
所以基本上,
获取现有帖子内容get_post_field
使用上载图像wp_insert_attachment
这将为您提供图像ID,从帖子内容中获取图像大小和altwp_get_attachment_image
用新图像html替换旧图像占位符当所有图像占位符都替换为img标记时,使用将修改后的帖子内容保存到DBwp_update_post
可以选择将任何图像设置为后期缩略图/特色图像
set_post_thumbnail
.
$post_id = 1234;
$images = array(\'filename1.png\', \'filename2.png\', ... \'filename10.png\');
// Get post content
$post_content = get_post_field( \'post_content\', $post_id );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
foreach($images as $name) {
$attachment = array(
\'guid\'=> $wp_upload_dir[\'url\'] . \'/\' . basename( $name ),
\'post_mime_type\' => \'image/png\',
\'post_title\' => \'my description\',
\'post_content\' => \'my description\',
\'post_status\' => \'inherit\'
);
/**
* STEP 1
* add images as attachments to WordPress
*/
$image_id = wp_insert_attachment($attachment, $name, $post_id);
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . \'wp-admin/includes/image.php\' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $image_id, $name );
wp_update_attachment_metadata( $image_id, $attach_data );
/**
* STEP 2
* Grab image data from $post_content
*/
// strpos() + substr() maybe?
$width = 123;
$height = 123;
$alt = \'Hello\';
/**
* STEP 3
* get html markup for image
*/
// Let WP generate the html markup for the image, adjust size as needed (thumbnail,medium,large,full,array(width,height))
$image_html = wp_get_attachment_image( $image_id, array( $width, $height ), false, array( \'alt\' => $alt ) );
/**
* STEP 4
* Replace placeholders in content with img markup
*/
preg_replace( $pattern, $image_html, $post_content ) // I don\'t understand regex well enough to give an example, so you need to figure it out yourself
/**
* OPTIONAL
* set image as featured
*/
if ( $name === \'example\' ) {
set_post_thumbnail( $post_id, $image_id );
}
}
/**
* STEP 5
* Update post content
*/
$post_with_imported_images = array(
\'ID\' => $post_id,
\'post_content\' => $post_content,
);
wp_update_post( $post_with_imported_images );
EDIT 这应该是可行的,也许只需稍加调整,至少在经典编辑器中是这样。我对古腾堡不太确定,因为我没怎么研究它。