Hiding Page Templates in the Admin

With the latest version of Portfolio Press I needed certain page templates to only be available if the Portfolio Post Type Plugin is installed. This is because those page templates work specifically with portfolio post types and are ineffective without the plugin.

Unfortunately there is no filter for page templates in core (though there are some patches). The PHP workarounds I’ve seen are convoluted and brittle, so I decided to tackle this instead with javascript.

Here’s the enqueue I used from the theme:

/**
 * Removes page templates that require the Portfolio Post Type.
 *
 * This is an ugly hack until post template filters appear in core:
 * https://core.trac.wordpress.org/ticket/13265
 */
function portfoliopress_page_template_mod( $hook ) {
    if ( class_exists( 'Portfolio_Post_Type' ) )
        return;
    if ( 'post.php' != $hook )
        return;
    wp_enqueue_script( 'portfoliopress_page_template_mod', esc_url( get_template_directory_uri() . '/js/admin-page-template-mod.js' ) );
}
add_action( 'admin_enqueue_scripts', 'portfoliopress_page_template_mod' );

You’ll notice that if class_exists( ‘Portfolio_Post_Type’ ) the js doesn’t load. I also make sure I’m on the post hook so unnessary javascript doesn’t get loaded on every admin page.

Javascript

In this example I am removing two templates from the #page-template select box: ‘templates/portfolio.php’ and ‘templates/full-width-portfolio.php’. The option isn’t hidden if it has already been selected (i.e. when the plugin was previously active).

jQuery(document).ready(function ($) {

	var select = $('#page_template');

	if ( ! select ) {
		return;
	}

	var templates = [ 'templates/portfolio.php', 'templates/full-width-portfolio.php' ];

	templates.forEach( function( element ) {
		var option = select.find( 'option[value="' + element + '"]' );
		if ( !option.is(':selected') ) {
			option.remove();
		}
	});

});

Conclusion

This is definitely a hack. The overhead of an extra javascript file to make this small markup change is extreme. Hopefully the core patch gets into an upcoming version of WordPress.

If you want to see the full code in Portfolio Press, it’s available on GitHub.

1 Response

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>