Toggle admin metabox based upon chosen page template

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?

Related posts

Leave a Reply

2 comments

  1. 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);
    
  2. Rather than rendering the metabox only to hide it with jQuery you can use this. The only difference being that the hiding/showing of the metabox requires selecting ‘Update’ after changing the drop-down field.

    function add_meta_box() {
        global $post;
        if(!empty($post)) {
            $pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);
    
            if($pageTemplate == 'your-page-template-here.php' ) {
                add_meta_box( $id, $title, $callback, 'page', $context, $priority, $callback_args );
            }
        }
    }
    add_action( 'add_meta_boxes', 'add_meta_box' );
    

    Just update lines 6 and 7 as desired.