Skip to content

Instantly share code, notes, and snippets.

@ryanshoover
Created August 16, 2018 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanshoover/fd5fad5fb6112663dcf5b48f753006fb to your computer and use it in GitHub Desktop.
Save ryanshoover/fd5fad5fb6112663dcf5b48f753006fb to your computer and use it in GitHub Desktop.
Plugin to add the page template to the Pages admin
<?php
/**
* Show Page Templates
*
* @package show-page-templates
* @author ryanshoover
* @license Proprietary
*
* @wordpress-plugin
* Plugin Name: Show Page Templates
* Plugin URI: wordpress.org
* Description: Shows page templates filterable
* Version: 0.1.0
* Author: ryanshoover
* Author URI: ryan.hoover.ws
* Text Domain: show-page-templates
* License: Proprietary
*/
namespace ShowPageTemplates;
function register( $columns ) {
$columns[ 'page-template'] = __( 'Template', 'show-page-templates' );
return $columns;
}
add_filter( 'manage_page_posts_columns', __NAMESPACE__ . '\register' );
function sortable( $columns ) {
$columns['page-template'] = 'page-template';
return $columns;
}
add_filter( 'manage_edit-page_sortable_columns', __NAMESPACE__ . '\sortable' );
function filter_dropdown(){
if ( empty( $_GET['post_type'] ) || 'page' !== $_GET['post_type'] ) {
return;
}
$templates = array_flip( get_page_templates( null, 'page' ) );
$selected_value = ! empty( $_GET['page-template'] ) ? esc_attr( $_GET['page-template'] ) : '';
?>
<select name="page-template">
<option value="">All Templates</option>
<?php
foreach ( $templates as $value => $name ) :
?>
<option
value="<?php esc_attr_e( $value ); ?>"
<?php selected( $value, $selected_value, true ); ?>
>
<?php esc_html_e( $name ); ?>
</option>
<?php
endforeach;
?>
</select>
<?php
}
add_action( 'restrict_manage_posts', __NAMESPACE__ . '\filter_dropdown' );
function content( $column, $post_id ) {
static $templates;
$templates = $templates ?: array_flip( get_page_templates( null, 'page' ) );
if ( 'page-template' === $column ) {
$template = get_page_template_slug( $post_id );
$template_name = ! empty( $templates[ $template ] ) ? $templates[ $template ] : 'Default';
esc_html_e( $template_name, 'show-page-templates' );
}
return $column;
}
add_filter( 'manage_pages_custom_column', __NAMESPACE__ . '\content', 10, 2 );
function get_posts( $query ) {
if ( ! is_admin() ) {
return;
}
if ( 'page-template' == $query->get( 'orderby' ) ) {
$query->set( 'meta_key', '_wp_page_template' );
$query->set( 'orderby', 'meta_value' );
}
if ( ! empty( $_GET['page-template'] ) ) {
$meta_query = $query->get( 'meta_query' );
$meta_query = $meta_query ?: [];
$meta_query[] = [
'key' => '_wp_page_template',
'value' => esc_attr( $_GET['page-template'] ),
];
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', __NAMESPACE__ . '\get_posts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment