How to hide a template in Wordpress?
php, wordpress, wordpress-theming
Solution
Update - a word of caution as pointed out by andrew in the comments below:
Use this code with caution, If you have any pages using the template that you removed from the select, updating the page will cause it to revert to the default template
I'm not sure if there is a PHP way of doing this - you'll have to look in the `WP_Theme` class, but from my first look it might not be possible because in order to get all templates, the class utilizes an internal function called `scandir()` which scans the current theme directory and gets all `.php` files from there. It then looks for the corresponding `Template Name:` identifier and if it's present it gets added to the templates list.
So instead I suggest, that you add a little JS that will remove this option from the page template select. Here's a code snippet:
function my_remove_page_template() {
global $pagenow;
if ( in_array( $pagenow, array( 'post-new.php', 'post.php') ) && get_post_type() == 'page' ) { ?>
<script>
(function($){
$(document).ready(function(){
$('#page_template option[value="sidebar-page.php"]').remove();
})
})(jQuery)
</script>
<?php
}
}
add_action('admin_footer', 'my_remove_page_template', 10);
This will remove the template `sidebar-page.php` from the dropdown. The conditionals are so that the script is only added on add and edit screens of pages.
Adjust to your case and enjoy :)
Problem
Is there a way to hide a template file in admin? For example I have a template that should only be available if a specific plugin is installed, and I already know how to check if plugin is active. But how do I hide the template? For example I want to hide "Blogger Redirection"-template bellow: I have found several links, but all of the solutions seems deprecated. EDIT: If anyone is interested in how I check if pluin is active I do it with the following function: ``` function isPluginActive($plugin){ if ( in_array( $plugin, apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) { return true; } return false; } ```