选择模板时显示的自定义元框

时间:2012-04-24 作者:smogg

Possible Duplicate:
Toggle admin metabox based upon chosen page template

有人从下拉列表中选择某个模板后,是否可以立即更改编辑器屏幕?我需要一个仅在页面模板为page-portfolio.php. 我知道我可以使用此代码:

$post_id = $_GET[\'post\'] ? $_GET[\'post\'] : $_POST[\'post_ID\'] ;

$template_file = get_post_meta($post_id,\'_wp_page_template\',TRUE);

然后使用if 声明。问题是它不能立即工作。如果没有非常复杂的编码,当用户更改模板列表而不保存时,是否可以“捕捉”这一时刻?

1 个回复
SO网友:brasofilo

我知道插件Advanced Custom Field 确实如此。正在检查its code, 我看到他使用jQuery处理这个问题。作为参考,我认为这应该对您有用:

/* 
 * Change Meta Box visibility according to Page Template
 *
 * Observation: this example swaps the Featured Image meta box visibility
 *
 * Usage:
 * - adjust $(\'#postimagediv\') to your meta box
 * - change \'page-portfolio.php\' to your template\'s filename
 * - remove the console.log outputs
 */

add_action(\'admin_head\', \'wpse_50092_script_enqueuer\');

function wpse_50092_script_enqueuer() {
    global $current_screen;
    if(\'page\' != $current_screen->id) return;

    echo <<<HTML
        <script type="text/javascript">
        jQuery(document).ready( function($) {

            /**
             * Adjust visibility of the meta box at startup
            */
            if($(\'#page_template\').val() == \'page-portfolio.php\') {
                // show the meta box
                $(\'#postimagediv\').show();
            } else {
                // hide your meta box
                $(\'#postimagediv\').hide();
            }

            // Debug only
            // - outputs the template filename
            // - checking for console existance to avoid js errors in non-compliant browsers
            if (typeof console == "object") 
                console.log (\'default value = \' + $(\'#page_template\').val());

            /**
             * Live adjustment of the meta box visibility
            */
            $(\'#page_template\').live(\'change\', function(){
                    if($(this).val() == \'page-portfolio.php\') {
                    // show the meta box
                    $(\'#postimagediv\').show();
                } else {
                    // hide your meta box
                    $(\'#postimagediv\').hide();
                }

                // Debug only
                if (typeof console == "object") 
                    console.log (\'live change value = \' + $(this).val());
            });                 
        });    
        </script>
HTML;
}

结束