概要
get_lastpostdate
フィルタは、投稿記事の最終投稿日時を取得する際に使用されるフィルタです。このフィルタを使うことで、デフォルトの動作を変更したり、追加の情報を付加したりすることができます。一般に、次のような機能を実装する際に利用されます:
- 最終投稿日時のフォーマット変更
- 特定の条件に基づく日時のカスタマイズ
- SEO向けのカスタムメタデータの追加
- 異なるカスタム投稿タイプに対応した最終投稿日時の取得
- ウィジェットやショートコードでの表示調整
- APIレスポンスにおける最終投稿日時の最適化
- 開発者によるデバッグ情報のエクスポート
- プレゼンテーション用のデータフィルタリング
構文
apply_filters( 'get_lastpostdate', $date, $timezone, $post_type );
パラメータ
$date
(string): 現在の最終投稿日時。この値がフィルタによって変更される可能性があります。$timezone
(string): タイムゾーンを指定します。$post_type
(string): 投稿タイプ(例:’post’, ‘page’)。
戻り値
フィルタリングされた最終投稿日時(string)。
関連する関数
使用可能なバージョン
get_lastpostdate
フィルタは WordPress 1.5 以降で使用可能です。
コアファイルのパス
wp-includes/post.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('get_lastpostdate', 'custom_last_post_date_format', 10, 3);
function custom_last_post_date_format($date, $timezone, $post_type) {
return date('Y年m月d日', strtotime($date));
}
このコードは、最終投稿日時をより日本語的な形式(例:2023年10月01日)で返します。
サンプルコード2: 特定の投稿タイプの最終投稿日時を取得する
add_filter('get_lastpostdate', 'custom_post_type_last_post_date', 10, 3);
function custom_post_type_last_post_date($date, $timezone, $post_type) {
if ($post_type === 'custom_type') {
// カスタム投稿タイプ 'custom_type' の最終投稿日を変更
return current_time('Y-m-d H:i:s');
}
return $date;
}
このコードでは、カスタム投稿タイプに対する最終投稿日時を現在の日時に置き換えています。
サンプルコード3: タイムゾーンに基づいた投稿日時を設定する
add_filter('get_lastpostdate', 'filter_last_post_date_timezone', 10, 3);
function filter_last_post_date_timezone($date, $timezone, $post_type) {
if ($timezone === 'Asia/Tokyo') {
return date('Y/m/d H:i:s', strtotime($date . ' +9 hours'));
}
return $date;
}
このコードは、指定されたタイムゾーンが東京の場合に投稿日時を9時間進める機能を提供します。
サンプルコード4: 最終投稿日時をカスタムメタと統合する
add_filter('get_lastpostdate', 'add_custom_meta_to_last_post_date', 10, 3);
function add_custom_meta_to_last_post_date($date, $timezone, $post_type) {
$custom_meta = get_post_meta(get_the_ID(), 'custom_meta_key', true);
return $date . ' - Custom Meta: ' . esc_html($custom_meta);
}
このコードは、最終投稿日時にカスタムメタ情報を追加して表示します。
サンプルコード5: RSSフィード内での最終投稿日時の変更
add_filter('get_lastpostdate', 'customize_rss_feed_last_post_date', 10, 3);
function customize_rss_feed_last_post_date($date, $timezone, $post_type) {
if (is_feed()) {
return date('D, d M Y H:i:s O', strtotime($date));
}
return $date;
}
このコードでは、RSSフィード内で最終投稿日時のフォーマットをRFC 2822形式に変更しています。