I've created a Custom Post Type and a Custom Taxonomy.
In WP Admin, how can I limit amount of taxonomy terms that are added to the custom post type? I want to add no more than one tag into the post. After adding one tag, adding more should be disabled or a message should appear.
Any help appreciated much.
I've created a Custom Post Type and a Custom Taxonomy.
In WP Admin, how can I limit amount of taxonomy terms that are added to the custom post type? I want to add no more than one tag into the post. After adding one tag, adding more should be disabled or a message should appear.
Any help appreciated much.
You can do it with jQuery with easyly. Count your tags and limit it!
$(document).ready(function(){ var L = 10; var $items = $('#post_tag .tagchecklist span'); if($items.length == L){ $("#post_tag").addClass("disable"); // or alert("ok") } });
To limit the number of taxonomy terms that can be added to a custom post type in WordPress, you can use a combination of JS and WP
function limit_taxonomy_terms($taxonomy, $post_type, $limit = 1) {
// JavaScript for Admin Interface
add_action('admin_footer', function() use ($taxonomy, $post_type, $limit) {
global $pagenow;
// Check if we are on the edit page of the specified post type
if ($pagenow === 'post.php' && isset($_GET['post']) && get_post_type($_GET['post']) === $post_type) {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
// Check when a term is added to the taxonomy
$(document).on('change', '#<?php echo $taxonomy; ?>', function() {
var termCount = $(this).find('option:selected').length;
// If the maximum limit is reached, disable input field or display a message
if (termCount >= <?php echo $limit; ?>) {
// Disable input field or display a message
// For example:
// $(this).prop('disabled', true);
// or
alert('You can only add <?php echo $limit; ?> term(s).');
}
});
});
</script>
<?php
}
});
// Backend validation to restrict terms assignment
add_action('save_post', function($post_id) use ($taxonomy, $limit) {
$terms = wp_get_post_terms($post_id, $taxonomy);
$term_count = count($terms);
// If the number of assigned terms exceeds the limit, display an error message
if ($term_count > $limit) {
wp_die(sprintf(__('You can only assign %d term(s) to this post.'), $limit));
}
}, 10, 1);
}
// Usage example: Limit 'category' taxonomy terms for 'post' post type to 2 terms
limit_taxonomy_terms('category', 'post', 2);