問題描述

我一直在 Wordpress 中發現圖像,文件,鏈接等都插入到 WordPress 中,絕對 URL 而不是相對 URL 。相對 URL 更方便切換域名,在 http 和 https 之間進行更改。今天我發現如果您使用相對 URL 定義 WP_CONTENT_URL,那麼當您將文件插入到帖子中時,它們使用 src 的相對 url 而不是絕對 URL 。只是我一直想要的!但官方 Wordpress 文檔説您應該使用完整的 URI,如果您正在定義 WP_CONTENT_URL 。

WordPress codex says

Set WP_CONTENT_URL to the full URI of this directory (no trailing slash), e.g.

define( 'WP_CONTENT_URL', 'http://example/blog/wp-content'); 

當我使用相對網址 (例如,

define( 'WP_CONTENT_URL', '/my-content-folder');

但是使用相對 URI 有什麼問題嗎?我只是認為 Wordpress 的原因一定是説明它應該用一個完整的 URI 來定義。

最佳解決方案

我認為這只是一個核心開發者可以/應該回答的問題。我研究發現核心票#17048:URLs delivered to the browser should be root-relative 。在哪裏可以找到主要核心開發商 Andrew Nacin 解釋的原因。他還鏈接到 this [wp-hackers] thread 。在這兩個鏈接上,這些是為什麼 WP 不使用相對 URL 的關鍵報價:

核心票:

  • Root-relative URLs aren’t really proper. /path/ might not be WordPress, it might be outside of the install. So really it’s not much different than an absolute URL.

  • Any relative URLs also make it significantly more difficult to perform transformations when the install is moved. The find-replace is going to be necessary in most situations, and having an absolute URL is ironically more portable for those reasons.

  • absolute URLs are needed in numerous other places. Needing to add these in conditionally will add to processing, as well as introduce potential bugs (and incompatibilities with plugins).

[wp-hackers] 線程

  • Relative to what, I’m not sure, as WordPress is often in a subdirectory, which means we’ll always need to process the content to then add in the rest of the path. This introduces overhead.

  • Keep in mind that there are two types of relative URLs, with and without the leading slash. Both have caveats that make this impossible to properly implement.

  • WordPress should (and does) store absolute URLs. This requires no pre-processing of content, no overhead, no ambiguity. If you need to relocate, it is a global find-replace in the database.


而且,在個人筆記中,我發現主題和插件不好的代碼,當
WP_CONTENT_URL
被定義時就會中斷。他們不知道這可以設置,並假設這是真的:WP.URL /wp-content /WhatEver,並不總是這樣。有些事情會一路衝破。


插件 Relative URLs(在 edse 的答案中鏈接),將 wp_make_link_relative 功能應用於動作鈎 template_redirect 中的一系列過濾器。這是一個很簡單的代碼,似乎是一個不錯的選擇。

次佳解決方案

<?php wp_make_link_relative( $link ) ?>

Convert full URL paths to relative paths.

Removes the http or https protocols and the domain. Keeps the path ‘/’ at the beginning, so it isn’t a true relative link, but from the web root base.

Reference: WordPress Codex

第三種解決方案

我同意 Rup 。我想主要是為了避免相對路徑的混淆。我認為 wordpress 可以從頭開始使用相對路徑,但使用多個插件時可能會出現問題,主題是如何配置的

在測試服務器上工作時,我曾經使用過此插件的相對路徑:

Root Relative URLs
Converts all URLs to root-relative URLs for hosting the same site on multiple IPs, easier production migration and better mobile device testing.

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。