概要
trailingslashit
関数は、与えられた文字列の末尾にスラッシュ(”/”)を追加する機能を持っています。この関数は、URLやファイルパスを統一的な形式に整える際によく使われるため、特にウェブ開発やテーマ・プラグインの開発時に重宝されます。主に以下のような機能を実装する際に利用されます。
- URLの統一性を保つ
- ディレクトリパスの整形
- REST APIエンドポイントの設定
- 内部リンクの生成
- webpackや静的ファイルのパス調整
- リダイレクト設定
- スラッグの処理
- ユーザー定義のパスの整形
構文
string trailingslashit( string $string );
パラメータ
$string
(string): スラッシュを追加したい文字列。
戻り値
$string
の末尾にスラッシュが追加された文字列が返されます。もしすでにスラッシュが末尾にある場合、元の文字列をそのまま返します。
関連する関数
使用可能なバージョン
- WordPress 1.5.0 以降で使用可能。
コアファイルのパス
wp-includes/formatting.php
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | 〇 |
wp_roles_init | |
setup_theme | |
after_setup_theme | 〇 |
set_current_user | |
init | 〇 |
register_sidebar | |
wp_loaded | 〇 |
send_headers | |
parse_query | |
pre_get_posts | |
wp | 〇 |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプル1: URLの整形
このサンプルでは、URLの末尾にスラッシュを追加します。
$url = 'https://example.com/path/to/resource';
$completed_url = trailingslashit($url);
echo $completed_url; // https://example.com/path/to/resource/
引用元: 自作
サンプル2: ディレクトリパスの整形
ファイルパスが正しい形式であることを確認します。
$path = '/var/www/html/myfolder';
$safe_path = trailingslashit($path);
echo $safe_path; // /var/www/html/myfolder/
引用元: 自作
サンプル3: REST APIエンドポイントの設定
REST APIのエンドポイントを適切に設定します。
$base_url = 'https://api.example.com/services';
$api_url = trailingslashit($base_url) . 'v1/users';
echo $api_url; // https://api.example.com/services/v1/users
引用元: 自作
サンプル4: 内部リンクの生成
ブログ内のリンクを正しい形式に整えます。
$link = 'your-post-slug';
$full_link = trailingslashit(home_url($link));
echo $full_link; // https://example.com/your-post-slug/
引用元: 自作
サンプル5: スラッグの処理
スラッグに対してスラッシュを付与します。
$slug = 'my-custom-slug';
$slug_with_slash = trailingslashit($slug);
echo $slug_with_slash; // my-custom-slug/
引用元: 自作
非推奨または削除されたバージョン
特定のワードプレスバージョンでこの関数が非推奨または削除された情報はありません。