webかたつむり ウェブデザインを勉強中 ウェブ初心者のおぼえがき

webかたつむり

WEB制作会社のフォトグラファー

wordpress absolute URLs

  • 既存のwordpressサイトの見栄えを含めた改修作業をすることになって、授業でwordpressを教わった時から、トラブルの原因と思われた、絶対パス参照の問題に再びぶちあたった。
  • そもそも、wordpressの開発者が意図してそのような設計にしているのだから、その意図を探りたくなる。
  • そこで、、、

https://core.trac.wordpress.org/ticket/17048

wordpress コア開発チームのやり取り

Description

Using absolute URLs are needed for email, and maybe RSS, and RPC.

For normal pages on a fresh install (default theme):

-Using absolute URLs like "http://domain.tld/path/file" (current behavior) breaks css and links if the server uses more then one domain/ip

-Using relative URLs like "../path/file" would likely break a lot and make WordPress unnecessarily complicated.

-Using root-relative URLs like "/path/file" is the correct design decision maximizing compatibility/functionality.

 

  • 絶対パスRSSなど、いくつかの箇所で必ず必要になってくる。
  • 複数のドメイン/IPを使用しているサーバーで、絶対パスを使用するとCSSやリンクが切れる。
  • 「../path/file」 のような相対パスはより多くのリンク切れを起こすだろうし、ワードプレスの構造が不必要に複雑する。
  • 互換性/機能性を最大化するのであれば、 「/path/file」 のようなルートパスを採用するのがよい。

上の提案に対して、、、

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.

As you said, 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).

Unfortunately, the opinion of those threads are skewed in the direction you mention due to most of them not really understanding the problem or the design decision (nor are most of them active core contributors or core developers). I've tried to cover a bit of the design decision on wp-hackers before, and I've been able to locate this reply of mine (the first part, in particular):

http://lists.automattic.com/pipermail/wp-hackers/2010-November/036195.html

 

f:id:ohta-felica:20170114131611p:plain

  •  ルートパスにしても、ワードプレスの外部を参照するのであれば、絶対参照とそんなに変わらないじゃない、、、
  • ワードプレスの移転に際して、皮肉なことにルートパスや相対パスよりも、絶対パスの書き換えの方が容易なケースが多いのかも、、、
  • 絶対参照が必要な部分は必ずあるので、条件付きで絶対参照する箇所があると、プロセスの負荷(オーバーヘッド)になったり、バグの原因となりやすい。

 

Why relative URLs should be forbidden for web developers • Yoast Dev Blog

 

以下のサイトで勉強させてもらいました。 

WordPress のURLはなぜ相対パスでなく絶対パスが用いられるのか - Lowaivill Tech Blog 

とはいえ、、、

参考として絶対パス相対パスへ変換するコードを以下に紹介しておきます。
以下のコードを functions.php に追記するだけです。

とのことです。ちょっと試してみます。

 

function delete_host_from_attachment_url($url) {

  $regex = '/^http(s)?:\/\/[^\/\s]+(.*)$/';

  if (preg_match($regex, $url, $m)) {

    $url = $m[2];

  }

  return $url;

}

add_filter('wp_get_attachment_url', 'delete_host_from_attachment_url');

add_filter('attachment_link', 'delete_host_from_attachment_url');