概要
wp_title
フィルタは、ページタイトルを変更またはカスタマイズするためのフックです。このフィルタを使用すると、ウェブサイトのSEOやユーザーエクスペリエンスを向上させるために、ページタイトルを動的に変更できます。以下に、このフィルタがどのような機能を実装する際によく使われるかを示します。
- SEO対策としてのタイトルカスタマイズ
- タイトルにブランド名やサイト名を追加
- 利用者のリクエストに基づくタイトル変更
- 特定の条件下でのタイトル変更(例:特定のカテゴリー、タグ、またはカスタム投稿タイプ)
- ページごとのメタディスクリプションとタイトルの一貫性を持たせる
- タイトルに日付や著者名を組み込む
- マルチ言語対応のためのタイトル調整
- ウェブサイトのテーマやスタイルに合わせたタイトルのスタイリング
構文
add_filter('wp_title', 'custom_wp_title');
パラメータ
$title
: 現在のページタイトルの文字列。
戻り値
- 変更またはカスタマイズされたページタイトルの文字列。
関連する関数
使用可能なバージョン
- WordPress 4.4以降で
wp_title
フィルタは非推奨となり、pre_get_document_title
フィルタが推奨されています。
コアファイルのパス
wp-includes/general-template.php
サンプルコード
サンプル 1: ページタイトルにサイト名を追加
このサンプルコードは、ページタイトルの末尾にサイト名を追加しています。
add_filter('wp_title', 'add_site_name_to_title');
function add_site_name_to_title($title) {
return $title . ' | ' . get_bloginfo('name');
}
引用元: https://developer.wordpress.org/reference/hooks/wp_title/
サンプル 2: 投稿タイプによるタイトル変更
特定の投稿タイプに対して異なるタイトルを表示するサンプルです。
add_filter('wp_title', 'custom_title_for_post_types');
function custom_title_for_post_types($title) {
if (is_singular('custom_post_type')) {
return '特別なタイトル - ' . get_the_title();
}
return $title;
}
引用元: https://developer.wordpress.org/reference/hooks/wp_title/
サンプル 3: カテゴリーアーカイブのタイトルカスタマイズ
カテゴリーアーカイブページに特別なタイトルを設定するサンプルです。
add_filter('wp_title', 'custom_category_title');
function custom_category_title($title) {
if (is_category()) {
return 'カテゴリー: ' . single_cat_title('', false);
}
return $title;
}
引用元: https://developer.wordpress.org/reference/hooks/wp_title/
サンプル 4: 検索結果ページのタイトル変更
検索結果ページに表示されるタイトルをカスタマイズするサンプルです。
add_filter('wp_title', 'custom_search_title');
function custom_search_title($title) {
if (is_search()) {
return '検索結果: ' . get_search_query();
}
return $title;
}
引用元: https://developer.wordpress.org/reference/hooks/wp_title/
サンプル 5: 固定ページのタイトルに日付を追加
固定ページのタイトルに現在の日付を付加するサンプルです。
add_filter('wp_title', 'add_date_to_title');
function add_date_to_title($title) {
if (is_page()) {
return $title . ' - ' . date('Y年n月j日');
}
return $title;
}
引用元: https://developer.wordpress.org/reference/hooks/wp_title/
この関数のアクションでの使用可能性
アクション | 使用可能 |
---|---|
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 | 〇 |
wp_title
フィルタは、WordPress 4.4以降では非推奨になりました。