WordPressのURLを相対パスにする
Raspberry Pi に WordPress を入れた時に困ること、
それは WordPress は中のリンクを「絶対パス」で表示してしまうこと。
IP アドレス固定の据え置き型なら、これでも何の問題もないのだが
ラズパイの様に、手軽に持ち運んで DHCP で、都度 IP が振られるような利用シーンだと
途端にスタイルシートやリンクなどが辿れなくなってしまう。
「絶対パス」を「相対パス」に置き換えるには以下の対応をする。
テーマの編集で functions.php を編集する。
ファイルの最後に以下のコードを追記する。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// 絶対パス→相対パス変換 class relative_URI { function __construct() { add_action('get_header', array(&$this, 'get_header'), 1); add_action('wp_footer', array(&$this, 'wp_footer'), 99999); } function replace_relative_URI($content) { $home_url = trailingslashit(get_home_url('/')); $top_url = preg_replace('/^(https?:\/\/.+?)\/(.*)$/', '$1', $home_url); return str_replace($top_url, '', $content); } function get_header(){ ob_start(array(&$this, 'replace_relative_URI')); } function wp_footer(){ ob_end_flush(); } } new relative_URI(); |
これでかなり持ち運びしやすくなったぞ。
その後の顛末
管理画面が絶対パスのままだった orz。こっちも相対パスにするにはフックを以下の様に修正する。
1 2 3 4 5 |
function __construct() { add_action('init', array(&$this, 'get_header'), 1); add_action('wp_footer', array(&$this, 'wp_footer'), 99999); add_action('admin_footer', array(&$this, 'wp_footer'), 99999); } |
init はフロントエンドでも管理画面でも呼び出される。
wp_footer はフロントエンドでのみ呼び出される。
admin_footer は管理画面でのみ呼び出される。
その後は、まあ大体問題なく使えるけれど、余裕があるなら wp_options の siteurl と home も相対パスにしておく。
例) http://localhost/wp → /wp
参考:
http://evm-label.com/2015/04/wordpress_path01/
http://2inc.org/blog/2012/02/03/1198/
テンプレートを開いたときに読み込まれるフックと順番