WordPress 技巧:自定义附件的固定链接

在默认情况下 WordPress 的附件的永久链接为,http://日志链接/attachment/attachment-name/,这样显得太长不好看,如果我们想定义为:http://siteurl/media/media-id/,怎么处理呢?可以将以下代码复制到当前主题的 functions.php 即可实现:


<?php
/*
Plugin Name:自定义附件的固定链接
Plugin URI: http://blog.wpjam.com/m/custom-attachment-permalink/
Description: 将附件的固定链接设置为:http://siteurl/media/media-id/
Version: 0.1
Author: Denis
Author URI: http://wpjam.com
*/
//设置附件的固定链接
add_filter('attachment_link','wpjam_attachment_link',10,2);
function wpjam_attachment_link($link,$post_id){
    return home_url('/media/'.$post_id.'/');
}

//设置附件的 rewrite 规则
add_action('generate_rewrite_rules', 'wpjam_generate_rewrite_rules');
function meitui_generate_rewrite_rules($wp_rewrite){

    $wp_rewrite->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;
}
标签:

热门文章