歲月留聲

如何把 WordPress 未使用 ID 利用起来?

老頭这个博客曾经到导入过其它站点数据,因此有大约 1600 个 post ID 跳过了没有使用,如何把 WordPress 未使用 ID 利用起来?笨办法是每次发表新文章,进去 phpMyAdmin 修改数据库,当然使用 sql 命令修改也行。

如何把 WordPress 未使用 ID 利用起来? - 第1张图片

「如何把 WordPress 未使用 ID 利用起来?:https://0xo.net/56」

手工方法终究太麻烦,有没有省事高效方法?答案是肯定有,参考:笛声 - 真正完美解决 wordpress 文章 ID 不连续问题,老頭以前也折腾过 WordPress 文章 ID 不连续这个问题,不过现在已经不在意了。

首先找出 WordPress 未使用 ID,文章、附件、页面、菜单均会占用 ID,一定要尽可能确保 ID 没有使用!比如老頭这里大概是 60 ~ 1588 这些 ID 没有使用。快速方法:如何快速获取 WordPress 博客所有已用 ID?

接着创建一个包含 2 列数据 Excel 表格:第一列是 ID 和文章标题,内容为 60 ~ 1588 这些数字,另一列是文章内容,随便写点就好,比如 draft。

「如何把 WordPress 未使用 ID 利用起来?:https://0xo.net/56」

如何把 WordPress 未使用 ID 利用起来? - 第2张图片

然后把这个 Excel 文件另存为 CVS 逗号分隔符文件备用(建议使用 vscode 等代码编辑文件另存一下,确保编码为 utf-8)。

温馨提示:进行以下操作前建议先备份!!!

「如何把 WordPress 未使用 ID 利用起来?:https://0xo.net/56」

接下来在 WordPress 博客数据库中创建一个 MySQL 表:名为 customposts,包含 post_title 和 post_content 两列。

ssh 登录 mysql,执行以下语句:

CREATE TABLE `wordpress`.`customposts` ( `post_title` text NOT NULL , `post_content` longtext NOT NULL ) ENGINE = InnoDB;

其中 wordpress 为博客数据库名字,请根据实际修改,post_title 和 post_content 类型也请根据数据实际修改,登录 phpMyAdmin 查看 posts 表结构可知。

「如何把 WordPress 未使用 ID 利用起来?:https://0xo.net/56」

如何把 WordPress 未使用 ID 利用起来? - 第3张图片

接着使用 phpMyAdmin 把 csv 文件导入到 customposts 表,浏览上传 csv 文件,一般默认即可,检查确保「字段分隔符」那里是一个英文逗号即可:

如何把 WordPress 未使用 ID 利用起来? - 第4张图片

点击「执行」导入。

接下来使用 WordPress 自带函数 wp_insert_post 根据 customposts 表数据创建文章即可。创建一个 createpost.php,代码如下:

<?php
require('./wp-blog-header.php');

//root 为数据库用户名,password 为数据库 root 用户密码
//也可以修改为 WordPress 博客数据库实际用户和对应密码
$con = mysqli_connect("localhost","root","password");
if (!$con){
die('Could not connect: ' . mysqli_error($con));
}

//根据 customposts 数据建立文章、草稿状态
//post_author 和 post_category 请根据实际修改
//wordpress 改为博客实际数据库名字
$result = mysqli_query($con, "SELECT * FROM wordpress.customposts") or die(mysqli_error($con));
while($line = mysqli_fetch_array( $result )) {
//create post
$thepost = array(
'import_id' => (int)$line['post_title'],
'post_title' => $line['post_title'],
'post_content' => $line['post_content'],
'post_status' => 'draft',
'post_author' => 1,
'post_category' => array(271)
);
wp_insert_post( $thepost );
}

文章 ID 和 标题相同,指定 ID 字段要使用 import_id,直接使用 ID 不会执行文件创建。(If you’re creating a post and the post ID doesn’t yet exist, using 'ID' => your_number will not create a new post. It will return blank, because it searched for the ID and it didn’t exist.)

如何把 WordPress 未使用 ID 利用起来? - 第5张图片

把 createpost.php 文件上传到 WordPress 博客根目录,赋予执行权限 chmod +x createpost.php,接着在 ssh 窗口中执行 /usr/local/php/bin/php createpost.php 稍等片刻,文章草稿就创建好了。

小坑:开始没注意笛声站长代码没有指定 ID,干完将近 1600 篇草稿检查才发现没有利用前面的 ID,整个人都蒙圈了,幸亏后来找到 import_id 顺利完成。

退出移动版