Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
    
If it doesn't need to be 'live' (i.e. changing the page template doesn't need to make the metabox appear / disappear immediately) see this related question: wordpress.stackexchange.com/questions/48611/… –  Stephen Harris Apr 11 '12 at 10:57
    
@StephenHarris Thanks for the comment. I wound up going with the WPAlchemy MetaBox class, which includes a "per template" option in the setup. –  Jonathan Wold Apr 11 '12 at 14:32

1 Answer 1

up vote 14 down vote accepted

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);
share|improve this answer
    
Wow, thank you! I'll be giving this a test soon and will report back accordingly. –  Jonathan Wold May 26 '11 at 15:11
    
So awesome...this is just what I needed. Worked perfect for me. Thank you!!! –  Ross Jun 14 '11 at 21:14
    
Sorry but I'm a real beginner in javascript and I know the stuff which is there is what I need, but it seems I'm not able to do things in the correct way...So I'm not sure to understand what I've to change in the javascript file.. Is it possible to have more explanation for a nooby like me? ;) –  user12082 Jan 15 '12 at 13:26

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.