Created
April 17, 2023 09:48
-
-
Save seemly/b567beaed00d852d076ef142a817059d to your computer and use it in GitHub Desktop.
Add a new 'Last Modified' column to WordPress admin Post list pages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function add_new_admin_column($columns) | |
{ | |
$columns['last_modified'] = 'Last Modified'; | |
return $columns; | |
} | |
add_filter('manage_posts_columns', 'add_new_admin_column'); | |
add_filter('manage_pages_columns', 'add_new_admin_column'); | |
// get Last Modified date of post content and at this value to post_meta | |
function show_last_modified_column($name, $post_id) | |
{ | |
if($name === 'last_modified') | |
{ | |
// Store the last modified date timestamp as a post meta option value | |
$last_modified_timestamp = get_the_modified_time('U'); | |
update_post_meta($post_id, 'last_modified', $last_modified_timestamp); | |
// Display the last modified date in a human readable format | |
// echo the result to be displayed in the cell | |
$date_format = 'Y/m/d'; | |
$time_format = 'g:i:s'; | |
$last_modified_human_readable = date($date_format . ' ' . $time_format . ' a', $last_modified_timestamp); | |
echo 'Last Modified <br/>' . $last_modified_human_readable; | |
} | |
} | |
add_action('manage_posts_custom_column', 'show_last_modified_column', 10, 2); | |
add_action('manage_pages_custom_column', 'show_last_modified_column', 10, 2); | |
function make_last_modified_column_sortable($columns) | |
{ | |
$columns['last_modified'] = 'last_modified'; | |
return $columns; | |
} | |
add_filter('manage_edit-post_sortable_columns', 'make_last_modified_column_sortable'); | |
add_filter('manage_edit-page_sortable_columns', 'make_last_modified_column_sortable'); | |
// Modify query and add 'last_modified' meta_key | |
function last_modified_column_orderby($query) | |
{ | |
if(!is_admin() || !$query->is_main_query()) | |
{ | |
return; | |
} | |
$orderby = $query->get('orderby'); | |
if('last_modified' === $orderby) | |
{ | |
$query->set('meta_key', 'last_modified'); | |
$query->set('orderby', 'meta_value_num'); | |
$query->set('last_modified', true); | |
} | |
} | |
add_action('pre_get_posts', 'last_modified_column_orderby'); | |
// append 'last_modified' var to query so it can used to change order for this column | |
function last_modified_column_request($vars) | |
{ | |
if(isset($vars['last_modified']) && $vars['last_modified']) | |
{ | |
$vars = array_merge($vars, [ | |
'meta_key' => 'last_modified', | |
'orderby' => 'meta_value_num', | |
]); | |
} | |
return $vars; | |
} | |
add_filter('request', 'last_modified_column_request'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment