WordPress 技巧:自定义附件的固定链接
在默认情况下 WordPress 的附件的永久链接为,http://日志链接/attachment/attachment-name/
,这样显得太长不好看,如果我们想定义为:http://siteurl/media/media-id/
,怎么处理呢?可以将以下代码复制到当前主题的 functions.php 即可实现:
rules = wpjam_remove_rewrite_rules($wp_rewrite->rules);
$wp_rewrite->extra_rules_top = wpjam_remove_rewrite_rules($wp_rewrite->extra_rules_top);
$new_rules = array();
$new_rules['media/([0-9]+)/?$'] = 'index.php?attachment_id=$matches[1]';
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
//删除附件原来的 rewrite 规则
function wpjam_remove_rewrite_rules($rules){
foreach ($rules as $key => $value) {
if( strpos($value, 'attachment') !== false ){
unset($rules[$key]);
}
}
return $rules;
}