I’d like to have a custom field interface show up only when a certain template is assigned to a particular WordPress page.
Any ideas?
I’d like to have a custom field interface show up only when a certain template is assigned to a particular WordPress page.
Any ideas?
The best way to approach this situation is via JavaScript. That way, whenever the selected value changes, you can instantly hide/show the related metabox.
Use wp_enqueue_script()
in functions.php
to load a custom JavaScript file in the admin area:
add_action('admin_enqueue_scripts', 'my_admin_script');
function my_admin_script()
{
wp_enqueue_script('my-admin', get_bloginfo('template_url').'/my-admin.js', array('jquery'));
}
The script itself, which requires jQuery, simply hides or shows a metabox based on the selected value in the page template dropdown list. In this example, I’m only showing the metabox for post thumbnails in case the default page template is selected:
(function($){
$(document).ready(function() {
var $page_template = $('#page_template')
,$metabox = $('#postimagediv'); // For example
$page_template.change(function() {
if ($(this).val() == 'default') {
$metabox.show();
} else {
$metabox.hide();
}
}).change();
});
})(jQuery);
And, just for fun, here’s a shorter, less verbose, version of the same script:
(function($){
$(function() {
$('#page_template').change(function() {
$('#postimagediv').toggle($(this).val() == 'default');
}).change();
});
})(jQuery);