wordpress 修改添加媒体时,链接改为相对链接

通过修改post.php文件:
进入wp-includes目录,找到post.php文件。
找到函数wp_get_attachment_url(不同版本的 WordPress 可能在不同行,如 3.7.1 版本在 4276 行),将其修改为如下代码:

function wp_get_attachment_url( $post_id = 0 ) {
    $file_dir = dirname(__FILE__);
    $server_root = $_SERVER['DOCUMENT_ROOT'];
    $file_dir = substr($file_dir, strlen($server_root));
    $file_dir = substr($file_dir, 0, -12);
    if ($file_dir!= '') {
        $file_dir = '/'.substr($file_dir, 1);
    }
    $post_id = (int) $post_id;
    if (! $post =& get_post($post_id))
        return false;
    $url = '';
    if ($file = get_post_meta($post->ID, '_wp_attached_file', true)) { //Get attached file
        if (($uploads = wp_upload_dir()) && false === $uploads['error']) { //Get upload directory
            if (0 === strpos($file, $uploads['basedir'])) //Check that the upload base exists in the file location
                // $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
                $url = $file_dir."/wp-content/uploads/".$file;
            elseif (false!== strpos($file, 'wp-content/uploads'))
                // $url = $uploads['baseurl']. substr($file, strpos($file, 'wp-content/uploads') + 18);
                $url = $file_dir."/wp-content/uploads/".$file;
            else
                // $url = $uploads['baseurl']."/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
                $url = $file_dir."/wp-content/uploads/".$file;
        }
    }
    if (empty($url)) //If any of the above options failed, Fallback on the GUID as used pre - 2.7, not recomended to rely upon this.
        $url = get_the_guid($post->ID);
    if ('attachment'!= $post->post_type || empty($url))
        return false;
    return apply_filters('wp_get_attachment_url', $url, $post->ID);
}
© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

    暂无评论内容