有没有一种方法可以在页面上显示特定的自定义字段';只有当他们选择了一个特定的模板时,Wordpress的管理界面


Is there a way to make sepcific custom fields show on a page's Wordpress admin interface only if they choose a specific template?

我想做这样的事情:

伪代码

if ( thisAdminPage.template === Template_Id_1 )
{
    showCustomFieldOption( "SpecialField" );
}
else hideCustomFieldOption( "SpecialField" );

然后,管理员用户会在该管理页面上看到一个文本框(或任何类型的字段)。但如果他们换成不同的模板,这个字段就会消失。

我该怎么做?

是的,正如WPSE的回答所示,只需要在页面编辑屏幕上添加一些jQuery,并注意模板下拉列表中的更改。

用于测试目的的元盒:

add_action( 'add_meta_boxes', function() {
    add_meta_box(
        'myplugin_sectionid',
        'Title', 
        function() {
            echo 'Test meta box';
        },
        'page'
    );
});

然后,在post.phppost-new.php页脚管理页中打印脚本。您必须调整页面模板名称的'onecolumn-page.php'和Meta-Box:的#myplugin_sectionid

foreach( array( 'post', 'post-new' ) as $hook )
    add_action( "admin_footer-$hook.php", 'enqueue_sopt_10564' );
function enqueue_sopt_10564()
{
    if( 'page' == get_current_screen()->id ) // Correct post type
    {
        echo <<<HTML
            <script type="text/javascript">
            jQuery(document).ready( function($) {
                /**
                 * Adjust visibility of the meta box at startup
                */
                if($('#page_template').val() == 'onecolumn-page.php') {
                    // show meta box
                    $('#myplugin_sectionid').show();
                    $("form#adv-settings label[for='myplugin_sectionid-hide']").show();
                } else {
                    // hide meta box
                    $('#myplugin_sectionid').hide();
                    $("form#adv-settings label[for='myplugin_sectionid-hide']").hide();
                }
                /**
                 * Live adjustment of the meta box visibility
                */
                $('#page_template').on('change', function(){
                    if($(this).val() == 'onecolumn-page.php') {
                        // show meta box
                        $('#myplugin_sectionid').show();
                        $("form#adv-settings label[for='myplugin_sectionid-hide']").show();
                    } else {
                        // hide meta box
                        $('#myplugin_sectionid').hide();
                        $("form#adv-settings label[for='myplugin_sectionid-hide']").hide();
                    }
                });                 
            });    
            </script>
HTML;
    } 
}

您可以使用Advanced Custom Fields插件。

从这里下载