完全没有经过测试,但我只是把它放在一起:
$post_data = array (
\'comment_status\' => \'closed\',
\'ping_status\' => \'closed\',
\'post_author\' => $author_id,
\'post_name\' => $slug,
\'post_title\' => $title,
\'post_status\' => \'publish\',
\'post_type\' => \'custom-post-type\',
);
$post_ID = wp_insert_post( $post_data );
if ( ! is_wp_error( $post_ID ) ) {
$post_meta = get_post_meta( $post_ID );
if ( $post_meta ) {
foreach ( $post_meta as $key => $value ) {
if ( preg_match(\'/(\\.jpg|\\.png)$/\', $value ) {
$file = file_get_contents( $value );
$tmpfname = tempnam( \'/tmp\', \'img\' );
$handle = fopen( $tmpfname );
fwrite( $handle, $file );
if ( getimagesize( $tmpfname ) ) {
$image_url = $value;
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = end( explode( \'/\', $image_url ) );
$fileName = end( explode( \'/\', $filename ) );
$uploadDir = end( explode( \'uploads\', $imageUrl ) );
$uploadDir = str_replace( $fileName, \'\', $uploadDir );
$filename = $fileName;
if ( wp_mkdir_p( $upload_dir[\'path\'] ) ) {
$file = $upload_dir[\'basedir\'] . $uploadDir . $filename;
} else {
$file = $upload_dir[\'basedir\'] . $uploadDir . $filename;
}
file_put_contents( $file, $image_data );
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array (
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => sanitize_file_name( $filename ),
\'post_content\' => \'\',
\'post_status\' => \'inherit\',
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_ID );
// Include image.php
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
fclose( $handle );
} else {
add_post_meta( $post_ID, $key, $value );
}
}
}
}
代码应该是自文档化的,但是如果您有任何问题或者它不起作用,请随时询问。