SYNCER

SYNCER

home_url() - ブログホームのURLを取得する

公開日:

home_url()は、現在のブログの、ホームのURLアドレスを取得する関数です。第1引数で追加のパスを指定できます。

構文

string home_url( string $path = '', string $scheme = null )

パラメータ

$path

初期値: ''

追加するパス。スラッグ(/)で始めること。

$scheme

初期値: null

通常、スキーム(httphttps)は環境によって自動判定されるが、ここで指定すると強制的にその通りにできる。relative を指定すれば、サーバー相対パスを取得できる。

"http"
スキームをhttpにする。
"https"
スキームをhttpsにする。
"relative"
URLではなく、サーバー相対パスにする。
null
http、またはhttpsを自動判定する。

返り値

string

絶対パスのURLアドレスを取得する。第2引数にrelativeを指定した場合だけ、サーバー相対パスを取得する。

関数

この関数内で利用している、別のWordPress関数です。

  • get_home_url() - 指定したブログの、ホームのURLを取得する。

サンプルコード

ホームのURLを取得する

ブログのホームのURLアドレスを取得します。

php

<?php
	// 実行
	$result = home_url() ;

	// 結果
	print_r( $result ) ;

結果 (出力内容) - PHP7.0.13

https://wp.syncer.jp

パスを追加する

第1引数に追加のパスを指定できます。スラッシュ(/)から指定して下さい。

php

<?php
	// 実行
	$result = home_url( "/category/animal/" ) ;

	// 結果
	print_r( $result ) ;

結果 (出力内容) - PHP7.0.13

https://wp.syncer.jp/category/animal/

スキームを指定する

第2引数でスキームを強制できます。「SSLサイトだけど事情があって、httpにしたい」などといった場合に有用です。

php

<?php
	// 実行
	$result = home_url( "/category/animal/", "http" ) ;

	// 結果
	print_r( $result ) ;

結果 (出力内容) - PHP7.0.13

http://wp.syncer.jp/category/animal/

相対パスを取得する

第2引数にスキームではなく"relative"を指定した場合、絶対パスではなくサーバー相対パスを取得できます。ホームのサーバー相対パスを指定する際はスラッシュ(/)だけを指定しましょう。

php

<?php
	// 実行
	$result = home_url( "/category/animal/", "relative" ) ;

	// 結果
	print_r( $result ) ;

結果 (出力内容) - PHP7.0.13

/category/animal/

ソースコード

wp-includes/link-template.php

/**
 * Retrieves the URL for the current site where the front end is accessible.
 *
 * Returns the 'home' option with the appropriate protocol. The protocol will be 'https'
 * if is_ssl() evaluates to true; otherwise, it will be the same as the 'home' option.
 * If `$scheme` is 'http' or 'https', is_ssl() is overridden.
 *
 * @since 3.0.0
 *
 * @param  string      $path   Optional. Path relative to the home URL. Default empty.
 * @param  string|null $scheme Optional. Scheme to give the home URL context. Accepts
 *                             'http', 'https', 'relative', 'rest', or null. Default null.
 * @return string Home URL link with optional path appended.
 */
function home_url( $path = '', $scheme = null ) {
	return get_home_url( null, $path, $scheme );
}

参考リンク