説明
the_title() は、現在の投稿のタイトルを出力する関数です。ループ内で使います。
基本構文
the_title( string $before = '', string $after = '', bool $display = true ): void|string
引数
$before:タイトルの前に付ける文字列$after:タイトルの後に付ける文字列$display:trueで出力、falseで戻り値として返す
戻り値
$display が false のときのみ文字列を返します。
使い方(サンプル)
// ループ内で使用
the_title( '<h1>', '</h1>' );
注意点
- 出力する関数なので
echoは不要です。値として取得したいときはget_the_title()を使います。 - パスワード保護や非公開の投稿には、自動で接頭辞が付きます。
- テンプレートファイル(
single.phpなど)のPHPブロック内に記述します。
実務での使いどころ
- ループの中で、投稿のタイトルをそのまま出力するとき。
- 前後にタグを付けて出力するとき(
the_title( '<h2>', '</h2>' ))。
よくあるミスと対処
- HTMLの属性値(
title=""やalt="")の中で使い、引用符でHTMLが壊れる。属性値にはthe_title_attribute()を使う。 - パスワード保護や非公開の投稿では、「保護中:」「非公開:」などの接頭辞が自動で付く。
- 値として使いたいのに、これを使っている。値の取得は
get_the_title()。
NG例
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <!-- タイトルに引用符があると、壊れる -->
OK例
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
使い分け早見表
| やりたいこと | 使うもの |
|---|---|
| タイトルを出力 | the_title() |
| タイトルを文字列で取得 | get_the_title() |
| 属性値に使う | the_title_attribute() |
関連項目
公式リファレンス:the_title() | Function | WordPress Developer Resources

コメント