如何将 WordPress 类别选择限制为一个? [英] How can I limit WordPress category selection to just one?
问题描述
我有自定义帖子类型和自定义分类设置 - 非常标准的东西.
I have a custom post type and a custom taxonomy setup - pretty standard stuff.
但是,我想知道如何限制我的客户在每个帖子中选择多个分类类别?
However, I would like to know how I can restrict my client from selecting more than one taxonomy category per post?
我不介意他们能够创建和删除分类类型,但我不希望他们选择多个.因为这些是复选框,所以它们可以.也许单选按钮可能有用?
I don't mind them being able to create and delete taxonomy types, but I don't want them selecting more than one. Because these are checkboxes, they CAN. Perhaps radio buttons might work?
我已经看到解决方案使用 jQuery 来更改这些字段,但它们似乎有点笨拙.执行此操作的最佳做法是什么?
I have seen solutions use jQuery to change these fields, but they seem a bit hacky. What's the best practice way to do this?
附件是我的自定义分类框的屏幕截图.
Attached, is a screenshot of my custom taxonomy box.
推荐答案
据我所知,我们必须使用 jQuery.它是hacky"但很容易工作,如果我的记忆力很好,纯 PHP/WP 解决方案真的很复杂.
这是必要的代码:
As far as I know, we have to use jQuery. It's "hacky" but works easily and a pure PHP/WP solution is really complex if my memory serves me well.
This is the necessary code:
jQuery("#categorychecklist input").each(function(){
this.type = 'radio';
});
我们必须在页面/wp-admin/post.php
和/wp-admin/post-new.php
上运行代码.它应该在加载时运行,然后在创建新类别时再次运行.为了解决新的类别问题,我使用了 MutationObserver
:
We have to run the code on the pages /wp-admin/post.php
and /wp-admin/post-new.php
. It should run on load and then run again if a new category is created. To solve the new category issue I used a 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
}
<小时>
相关:这个旧插件仍然有效完美解决子类层次问题.默认情况下,在WP中,选择一个子类别时,它不会在其父类别下显示,但在列表之上.它也是一个 jQuery 解决方案,由当时的 WP 核心开发人员编写.
Relevant: this old plugin still works perfectly to solve the issue of sub-categories hierarchy. By default in WP, when one sub-category is selected it doesn't show under its parent category but on top of the list. It's also a jQuery solution and written by a lead WP core developer at the time.
这篇关于如何将 WordPress 类别选择限制为一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!