5

我有一个自定义帖子类型和一个自定义分类设置 - 非常标准的东西。

但是,我想知道如何限制我的客户在每个帖子中选择多个分类?

我不介意他们能够创建和删除分类类型,但我不希望他们选择多个。因为这些是复选框,所以它们可以。也许单选按钮可能有用?

我已经看到解决方案使用 jQuery 来更改这些字段,但它们似乎有点 hacky。执行此操作的最佳实践方法是什么?

附件是我的自定义分类框的屏幕截图。

自定义分类

4

2 回答 2

0

我意识到这不是一个完整的答案,但是像使用下拉列表列出类别(或分类术语)这样简单的事情就可以了。我个人不知道,但必须有插件可以做到这一点。没有冒犯,但这确实让我觉得这是一个以前解决过的问题。

于 2012-07-12T19:38:59.460 回答
0

据我所知,我们必须使用 jQuery。它是“hacky”但很容易工作,如果我的记忆很好的话,一个纯 PHP/WP 解决方案真的很复杂。
这是必要的代码:

jQuery("#categorychecklist input").each(function(){
    this.type = 'radio';
});

我们必须在页面/wp-admin/post.php/wp-admin/post-new.php. 它应该在加载时运行,然后在创建新类别时再次运行。为了解决新类别问题,我使用了MutationObserver

foreach( array( 'post', 'post-new' ) as $hook )
    add_action( "admin_footer-$hook.php", 'convert_cats_to_radio' );

function convert_cats_to_radio(){
    global $post;
    if( $post->post_type !== 'post') // select your desired Post Type
        return;

    ?>
    <script type="text/javascript">
    function makeRadioButtons(){
        jQuery("#categorychecklist input").each(function(){
            this.type = 'radio';
        });
    }
    function newCategoryObserver(){
        // Example from developer.mozilla.org/en-US/docs/Web/API/MutationObserver
        var targetNode = document.getElementById('categorychecklist');
        var config = { attributes: true, childList: true, subtree: true };
        var callback = function(mutationsList) {
            for(var mutation of mutationsList) {
                if (mutation.type == 'childList') {
                    makeRadioButtons();
                }
            }
        };
        var observer = new MutationObserver(callback);
        observer.observe(targetNode, config);
    }
    newCategoryObserver();
    makeRadioButtons();
    </script>
    <?php
}

相关这个旧插件仍然可以完美地解决子类别层次结构的问题。By default in WP, when one sub-category is selected it doesn't show under its parent category but on top of the list. 它也是一个 jQuery 解决方案,由当时的主要 WP 核心开发人员编写。

于 2018-09-07T03:20:00.600 回答