【发布时间】:2016-01-14 14:59:37
【问题描述】:
我正在将 1000 多篇博文从旧的自定义数据库网站迁移到 wordpress。在使用 php 数组格式化每个帖子后,我正在测试如何将它们迁移到 wordpress。
我想做的是迁移带有特色图片的博客文章。经过一番研究,我使用了 wp_insert_post(),它只适用于文本内容>但是它不插入特色图像,所以我也需要使用 wp_insert_attachnment()。问题是当我在 foreach 循环中一起使用 wp_insert_post() 和 wp_insert_attachnment() 时,它不能正常工作。我的代码如下。如果有人对此问题有知识/方法,请给我建议。谢谢。
$wp_posts = array(
array(
'post_id' => '10',
'post_title' => 'Post Title 1',
'post_date' => '2015-06-22',
'post_content' => 'Post Content 1',
'post_imagePath' => 'http://localhost/test/wp-content/uploads/2016/01/image1.jpg'
),
array(
'post_id' => '11',
'post_title' => 'Post Title 2',
'post_date' => '2015-06-22',
'post_content' => 'Post Content 2',
'post_imagePath' => 'http://localhost/test/wp-content/uploads/2016/01/image2.jpg'
)
);
$filetype['type'] = 'image/jpeg';
$last = count($wp_posts) - 1;
foreach ($wp_posts as $i => $row){
$ID = $row['post_id'];
$title = $row['post_title'];
$content = $row['post_content'];
$postdate = $row['post_date']. " 12:00:00";
$imagePath = $row['post_imagePath'];
if (!get_page_by_title($title, 'OBJECT', 'post') ){
$my_post = array(
'ID' => $ID,
'post_title' => $title,
'post_content' => $content,
'post_date' => $postdate,
);
wp_insert_post( $my_post );
/* wp_insert_attachment */
$filetype = wp_check_filetype( basename( $imagePath ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $imagePath ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $imagePath ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $imagePath, $parent_post_id );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $imagePath );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $parent_post_id, $attach_id );
/* ./wp_insert_attachment */
}
}
【问题讨论】:
-
如果您在这里没有得到太多回应,最好将其发布在 Wordpress StackExchange 上:wordpress.stackexchange.com。
-
感谢您的建议!我会做的。