The pre_get_lastpostmodified WordPress PHP filter allows you to modify the return value of get_lastpostmodified()
before the query is executed.
Usage
add_filter('pre_get_lastpostmodified', 'your_function_name', 10, 3); function your_function_name($lastpostmodified, $timezone, $post_type) { // your custom code here return $lastpostmodified; }
Parameters
- $lastpostmodified (string|false): The most recent time that a post was modified in ‘Y-m-d H:i:s’ format, or false. Returning anything other than false will short-circuit the function.
- $timezone (string): Location to use for getting the post modified date. See
get_lastpostdate()
for accepted$timezone
values. - $post_type (string): The post type to check.
More information
See WordPress Developer Resources: pre_get_lastpostmodified
Examples
Change the date format of the last modified post
Change the date format of the last modified post to ‘d/m/Y’.
add_filter('pre_get_lastpostmodified', 'change_date_format', 10, 3); function change_date_format($lastpostmodified, $timezone, $post_type) { if ($lastpostmodified) { $lastpostmodified = date('d/m/Y', strtotime($lastpostmodified)); } return $lastpostmodified; }
Display a custom message if no posts are modified
Display a custom message if there are no modified posts.
add_filter('pre_get_lastpostmodified', 'no_modified_posts_message', 10, 3); function no_modified_posts_message($lastpostmodified, $timezone, $post_type) { if (!$lastpostmodified) { $lastpostmodified = 'No posts have been modified.'; } return $lastpostmodified; }
Add a fixed offset to the last modified date
Add a fixed offset of 7 days to the last modified date.
add_filter('pre_get_lastpostmodified', 'add_offset_to_last_modified', 10, 3); function add_offset_to_last_modified($lastpostmodified, $timezone, $post_type) { if ($lastpostmodified) { $lastpostmodified = date('Y-m-d H:i:s', strtotime($lastpostmodified . ' +7 days')); } return $lastpostmodified; }
Set a minimum last modified date
Ensure the last modified date is never older than 30 days.
add_filter('pre_get_lastpostmodified', 'set_minimum_last_modified_date', 10, 3); function set_minimum_last_modified_date($lastpostmodified, $timezone, $post_type) { if ($lastpostmodified) { $minimum_date = date('Y-m-d H:i:s', strtotime('-30 days')); if ($lastpostmodified < $minimum_date) { $lastpostmodified = $minimum_date; } } return $lastpostmodified; }
Filter last modified date based on a specific post type
Display the last modified date only for ‘product’ post type.
add_filter('pre_get_lastpostmodified', 'filter_last_modified_by_post_type', 10, 3); function filter_last_modified_by_post_type($lastpostmodified, $timezone, $post_type) { if ($post_type != 'product') { $lastpostmodified = false; } return $lastpostmodified; }
This code will only return the last modified date if the post type is ‘product’. For other post types, the filter will return false.