wordpress5.1 カテゴリをラジオボタンにして選択を1つに制限する方法

jQueryでattrして、setTimeoutで遅延実行
admin_print_footer_scripts でフック
radioのchangeイベントで valueをcookieに保存
publish_postフックで wp_set_object_terms 関数を実行

 
function your_function() { echo '<script>
//Cange_to_radio_button

function to_radio_button(){
var elem = jQuery("#editor .editor-post-taxonomies__hierarchical-terms-choice input");
jQuery(elem).ready( function () {
jQuery(elem).attr({"type":"radio","name":"radio-category"});
});
}

setTimeout(function(){
to_radio_button();
},1000);

jQuery(document).on("change", "input.editor-post-taxonomies__hierarchical-terms-input", function(){
if( jQuery(this).prop("checked")){
let category_number = jQuery(this).val();
document.cookie = "radio-category=" + category_number;
}
});
</script>';

}
add_action('admin_print_footer_scripts', 'your_function');

function replace_post_terms($post_id) {
$radio_category = (int)$_COOKIE['radio-category'];
wp_set_object_terms($post_id, $radio_category, 'category',false );
}
add_action('publish_post', 'replace_post_terms', 99, 1);

 

Categories:

Tags: