海阔凭鱼跃,天高任鸟飞!

天高任鸟飞

       

如何将WordPress固定链接格式修改为.html结尾

作者:     目录: WordPress     发表: 2015年10月07日

使用WordPress好几年了,感觉百度对使用WordPress搭建的网站一直不太友好,通过对比几个国内比较出名的个人博客,发现WordPress的固定链接结构可能存在一些问题,因此今天将网站URL结构修改成.html结构。

WordPress提供的URL结构有下面几种:

如何将WordPress固定链接格式修改为.html结尾

之前一直采用 自定义结构 http://renniaofei.com/%category%/%postname%/  的URL结构形式,为了优化URL结构,特意将其修改为 http://renniaofei.com/%category%/%postname%.html,即以.html结尾,具体见上图。

如果是新建的网站,设置完固定链接结构就可以大功告成了,但我的网站已发表553篇文章,里面存在大量的站内链接,如果人工逐篇修改的话,那工作量实在太大了,而且容易出现漏改及误改。

如何批量修改文章内的站内链接呢?只能对数据库进行批量更新,但更改URL结构后缀还不像换网站域名那么简单,只是批量替换一下对应的域名即可,更改URL结构需要使用正则表达式去匹配需要的网址,然后只更新匹配到的网址。

显然MySQL里的replace函数已经不能满足要求,后来考虑过MySQL的regexp正则表达式函数,但不能更新数据库内容,因此最终决定使用PHP来实现匹配URL的批量替换。

利用PHP批量更新数据库中正则表达式匹配到的网址的具体步骤如下:首先利用PHP读出数据表中指定字段的所有记录,然后使用PHP preg_replace 函数匹配指定模式的所有网址,最终更新数据表指定字段。

将文章内http://renniaofei.com/%category%/%postname%/格式的网址全部修改为http://renniaofei.com/%category%/%postname%.html的PHP源代码:

<?php header(“Content-type: text/html; charset=utf-8”);
$dbhost = ‘localhost’;
$dbuser = ‘用户名’;
$dbpass = ‘密码’;
$dbname = ‘数据库名’;

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (‘Error connecting to mysql’);
mysql_select_db($dbname);

$query = “SELECT ID, post_content FROM wp_posts WHERE post_type=’post’ and post_status=’publish’ order by ID DESC”;
mysql_query(“set names utf8”);
$result = mysql_query($query) or die(‘Error, query failed. ‘ . mysql_error());

//读取所有记录
while($row = mysql_fetch_array($result)){
list($ID, $post_content) = $row;
$string1=$post_content;

//匹配链接网址
$pattern = “{(\”http://renniaofei.com)/([a-zA-Z0-9_-]{1,})/([a-zA-Z0-9_-]{1,})(/\”)}”;
$replacement = “\${1}/\${2}/\${3}.html\””;
$string1= preg_replace($pattern, $replacement, $string1);

//匹配链接文本
$pattern = “{(http://renniaofei.com)/([a-zA-Z0-9_-]{1,})/([a-zA-Z0-9_-]{1,})/</a>}”;
$replacement = “\${1}/\${2}/\${3}.html</a>”;
$string1=preg_replace($pattern, $replacement, $string1);

//匹配目录和标签
$pattern = “{(\”http://renniaofei.com)/(category|tag)/([a-zA-Z0-9_-]{1,})(.html\”)}”;
$replacement = “\${1}/\${2}/\${3}\””;
$string1=addslashes(preg_replace($pattern, $replacement, $string1));

//更新数据表wp_posts里的字段post_content
$updateStr=”update wp_posts set post_content=’$string1’ WHERE ID=$ID”;
mysql_query($updateStr) or die(‘Error, updateStr failed. ‘ . mysql_error());
} ?>

将上面的PHP文件单独保存成一个文件,然后上传到服务器,打开此页面即可执行所有匹配网址的批量替换。

操作前,请将上面PHP源码中的数据库信息及域名修改成你自己的,并且一定要做好数据库数据备份。

发表评论