在建立一些网站的时候,可能需要搬移一些原来站点的数据或者需要从别的一些网站抓取一些文章数据等,这个时候就需要我们新建的这个站点有对应处理批量导入数据的接口。我们可以按下面的步骤来操作:
1、在wp-admin文件中新建一个php文件命名为daoru.php,里面复制下面的代码:
require_once __DIR__ . '/admin.php';
require_once ABSPATH . 'wp-admin/admin-header.php';
global $post_type, $post_type_object, $post,$wpdb;
require_once ABSPATH. 'wp-load.php';
// 检查是否通过了身份验证
if (!is_user_logged_in() || !current_user_can('edit_posts')) {
wp_die(__('Sorry, you are not allowed to access this page.'));
}
$num=10;
$querystr = "SELECT title,thumb,content,tag FROM wp_article as a,wp_article_data as b where a.itemid=b.itemid and a.itemid>=$fid and thumb!='' order by a.itemid desc limit 0,".$num;
$results = $wpdb->get_results($querystr);
//die(print_r($results));
$i=0;
while ($i< count($results)){
//echo $results[$i]->title."<br />";
// 文章数据
$xid = $results[$i]->ID;
$post_data = [
'post_title' => $results[$i]->title,
'post_content' => $results[$i]->content,
'post_status' => 'publish',
'post_author' => $current_user->ID,
'tags_input' => $results[$i]->tag
];
//过滤重复标题的数据
$art_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) as num FROM wp_posts where post_title='".$results[$i]->title."'"));
//die(print_r($art_count));
if($art_count<=0){
// 插入文章
$post_id = wp_insert_post($post_data);
//对应分类控制
$catid=rand(6,9);
wp_set_post_categories($post_id, $catid);
/* 图片数据
//$image_url = $results[$i]->thumb; // 图片URL
$image_url='https://www.aab.com/file/upload/202404/11/223123986.png';
// 上传图片
$attachment_id = media_sideload_image($image_url, $post_id);
if (is_wp_error($attachment_id)) {
echo '图片上传失败: ' . $attachment_id->get_error_message();
} else {
echo '文章和图片已发布,文章ID: ' . $post_id.'<br>';
}
*/
}
$i++;
}
unset($results);
echo '<font color=red>成功导入'.$i.'条数据</font>';
注:期中里面的wp_article,wp_article_data为外部站点的数据表。
2、接着在站点地址中输入/wp-admin/daoru.php即可开始导入外部站点数据了。
以上是设置的每次导入10条,大家可以自行修改$num的值,希望这个方法能帮到有需要的码友。