wp_get_document_title() の使い方|説明・引数・注意点

説明

wp_get_document_title() は、現在のページのドキュメントタイトル(title タグの中身)を返す関数です。

基本構文

wp_get_document_title(): string

引数

引数はありません。

戻り値

タイトル文字列。

使い方(サンプル)

echo esc_html( wp_get_document_title() );

注意点

  • pre_get_document_title や document_title_parts フィルターでカスタマイズできます。

実務での使いどころ

  • ページのタイトル(<title> に入る文字列)を、文字列として取得するとき。
  • メタタグ(og:title)などに、同じタイトルを使うとき。

よくあるミスと対処

  • add_theme_support( 'title-tag' ) が有効なテーマで、header.php に <title> を書き、二重になる。
  • 出力時に、エスケープしていない。
  • タイトルの形式を変えたいのに、文字列を、自分で連結している。document_title_parts フィルターで、変更する。

NG例

echo '<meta property="og:title" content="' . wp_get_document_title() . '">'; // エスケープしていない

OK例

echo '<meta property="og:title" content="' . esc_attr( wp_get_document_title() ) . '">';

使い分け早見表

関数 役割
wp_get_document_title() ページのタイトルを、文字列で取得する
wp_title() 古い方法で、タイトルを出力する
get_the_title() 投稿のタイトルを、取得する

関連項目

add_theme_support()、wp_title()

公式リファレンス:wp_get_document_title() | Function | WordPress Developer Resources

コメント

タイトルとURLをコピーしました