概要
the_date
フィルタは、投稿データの投稿日を表示する際に使用されます。このフィルタを使うことにより、配信される日付のフォーマットや内容をカスタマイズすることが可能です。このフィルタは、主に以下の機能を実装する際によく用いられます:
- 日付表示の形式を変更する
- 日付をローカライズする
- 特定の条件に基づいて日付を非表示にする
- 日付に特定のスタイルやクラスを追加する
- カスタム日付フォーマットを使用する
- ソーシャルメディア用に日付を調整する
- 条件に基づいて異なる日付を表示する
- 日付を特定のタイムゾーンで表示する
構文
add_filter('the_date', 'callback_function', 10, 2);
パラメータ
- $the_date (string): フィルタが適用される日付。
- $d (string): 日付形式。デフォルトは ‘Y年n月j日’。
戻り値
フィルタが適用された後の日付文字列。
関連する関数
使用可能なバージョン
the_date
フィルタは、WordPress 1.5以降で使用可能です。
コアファイルのパス
WP-includes/general-template.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: 日付フォーマットの変更
add_filter('the_date', 'custom_date_format', 10, 2);
function custom_date_format($the_date, $d) {
return date('F j, Y', strtotime($the_date)); // 日付を "月 日, 年" の形式に変更
}
このコードは、投稿の日付を “月 日, 年” という形式で表示します。
サンプルコード 2: 日付を非表示にする
add_filter('the_date', 'hide_date_for_certain_posts', 10, 2);
function hide_date_for_certain_posts($the_date, $d) {
if (is_single() && in_category('no-date')) {
return ''; // 特定のカテゴリに属する投稿の日付を非表示にする
}
return $the_date;
}
このコードは、特定のカテゴリに属する投稿の日付を非表示にします。
サンプルコード 3: 日付にCSSクラスを追加
add_filter('the_date', 'add_class_to_date', 10, 2);
function add_class_to_date($the_date, $d) {
return '<span class="custom-date">' . $the_date . '</span>'; // 日付にクラスを追加
}
このコードでは、日付を span
タグで囲み、custom-date
という CSS クラスを追加します。
サンプルコード 4: 日付をカスタムフォーマットで表示
add_filter('the_date', 'custom_display_date', 10, 2);
function custom_display_date($the_date, $d) {
return date('d-m-Y', strtotime($the_date)); // 日付を "日-月-年" の形式で表示
}
このコードは、投稿の日付を “日-月-年” という形式で表示します。
サンプルコード 5: 時間を含む日付を表示
add_filter('the_date', 'include_time_in_date', 10, 2);
function include_time_in_date($the_date, $d) {
return date('Y年n月j日 H:i', strtotime($the_date)); // 日付に時間を追加
}
このコードは、投稿の日付に時間も含めて表示します。