Last active
February 24, 2025 04:08
-
-
Save Kristjan-Reinsberg/10b7b8d1df37d3641cea2af45a433856 to your computer and use it in GitHub Desktop.
WP add columns to Posts, Pages, CPT (template path and last modified)
This file contains hidden or 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 | |
| //WHY THIS FILE? - Find templates fast and get better overview of a new project | |
| //Posts, Pages, CPT get columns: "template path" and "last modified" | |
| // Add custom columns | |
| function add_custom_columns($columns) { | |
| $columns['modified_date'] = 'Last Modified'; | |
| $columns['page_template'] = 'Page Template'; | |
| return $columns; | |
| } | |
| add_filter('manage_pages_columns', 'add_custom_columns'); | |
| add_filter('manage_posts_columns', 'add_custom_columns'); | |
| add_filter('manage_sector_posts_columns', 'add_custom_columns'); //CPT "sector" | |
| // Populate custom columns | |
| function show_custom_columns($column_name, $post_id) { | |
| if ($column_name == 'modified_date') { | |
| $modified_date = get_post_modified_time('F j, Y', false, $post_id); | |
| echo $modified_date; | |
| } elseif ($column_name == 'page_template') { | |
| $template = get_page_template_slug($post_id); | |
| if ($template) { | |
| echo $template; | |
| } else { | |
| echo 'Default Template'; //NB! | |
| } | |
| } | |
| } | |
| add_action('manage_pages_custom_column', 'show_custom_columns', 10, 2); | |
| add_action('manage_posts_custom_column', 'show_custom_columns', 10, 2); | |
| add_action('manage_sector_posts_custom_column', 'show_custom_columns', 10, 2); //CPT "sector" | |
| // Add sorting support | |
| function custom_columns_sortable($columns) { | |
| $columns['modified_date'] = 'modified'; | |
| return $columns; | |
| } | |
| add_filter('manage_edit-page_sortable_columns', 'custom_columns_sortable'); | |
| add_filter('manage_edit-post_sortable_columns', 'custom_columns_sortable'); | |
| add_filter('manage_edit-sector_sortable_columns', 'custom_columns_sortable'); //CPT "sector" | |
| // Modify query | |
| function sort_by_custom_columns($query) { | |
| if (!is_admin()) { | |
| return; | |
| } | |
| $orderby = $query->get('orderby'); | |
| if ($orderby == 'modified') { | |
| $query->set('orderby', 'modified'); | |
| } | |
| } | |
| add_action('pre_get_posts', 'sort_by_custom_columns'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment