对于习惯使用ID作为WordPress固定链接的用户而言,因为WordPress特殊的ID计算模式,中间其他元素例如图片等附件往往会占用ID,这就使得前端展示的文章ID很多时候都不连续,对于强迫症用户而言,看起来不是很舒服。安全性上而言,ID形式的固定链接容易被非搜索引擎的爬虫抓取到,采集网站内容,而使用文章标题别名作为固定链接的话,纯中文会让URL长度超标,手动修改的话又过于麻烦,这里的话提供两种使用文章别名作为固定链接且自动转换文章别名为MD5的方式,一则文章url长度更加容易控制,二则很长程度上避免了一些垃圾爬虫的抓取与采集。
方法一:使用wp slup md5code插件,在WordPress官方下载即可。
方法二:将以下代码复制到当前主题的function.php文件中
//WordPress标题别名自动MD5 //原文地址:https://www.ufcn.cn/jiaocheng/548073/ if (!class_exists('wp_slup_md5code')): class wp_slup_md5code { var $post_title = ''; var $post_type = ''; function wp_slup_md5code() { global $wp_version; add_filter('type_save_pre', array(&$this, 'get_post_type'), 0); add_filter('title_save_pre', array(&$this, 'get_post_title'), 0); add_filter('name_save_pre', array(&$this, 'set_post_name'), 0); if ($wp_version > 2.4 && strpos($_SERVER['REQUEST_URI'], 'admin-ajax.php') > 0 && $_POST['action'] === 'sample-permalink') { add_filter('sanitize_title', array(&$this, 'w25_ajax_slug'), 0); register_shutdown_function(array(&$this, 'w25_ajax_remove')); } } function get_post_type($type) { $this->post_type = $type; return $type; } function get_post_title($title) { $this->post_title = $title; return $title; } function set_post_name($name) { if (strcmp('post', $this->post_type) == 0) { $name = $this->md5_encoding($this->post_title); } return $name; } function w25_ajax_slug($name) { remove_filter('sanitize_title', array(&$this, 'w25_ajax_slug'), 0); if (strcmp('post', $_POST['post_type']) == 0) { $name = $this->md5_encoding($_POST['new_title']); } add_filter('sanitize_title', array(&$this, 'w25_ajax_slug'), 0); return $name; } function w25_ajax_remove() { remove_filter('sanitize_title', array(&$this, 'w25_ajax_slug'), 0); } private function md5_encoding($str) { $str = trim(strip_tags($str)); if (strlen($str) == 0) { return $str; } $str = mb_convert_encoding($str, 'UTF-8'); $md5_str = md5($str); $md5_str = substr($md5_str, 8, 16); return $md5_str; } } endif; $wp_slup_md5code = new wp_slup_md5code();