How to make a tag description required How to make a tag description required wordpress wordpress

How to make a tag description required


Edit tag:

When editing tag, WordPress call wp_update_term. But there're no filters or AJAX call, so we must use get_term() which is called by wp_update_term():

add_filter('get_post_tag', function($term, $tax){    if ( isset($_POST['description']) && empty($_POST['description']) ) {        return new \WP_Error('empty_term_name', __('Tag description cannot be empty!', 'text-domain'));    } else {        return $term;    }}, -1, 2);

We also need to update term_updated_message to make the error clear:

add_filter('term_updated_messages', function($messages){    $messages['post_tag'][5] = sprintf('<span style="color:#dc3232">%s</span>', __('Tag description cannot be empty!', 'text-domain'));    return $messages;});

Because WordPress hardcoded the notice message div, I used inline css to make the error look like a waring. Change it to your preference.


Add new tag:

The AJAX request calls wp_insert_term so we can use pre_insert_term filter. Try this in your functions.php

add_filter('pre_insert_term', function($term, $tax){    if ( ('post_tag' === $tax) && isset($_POST['description']) && empty($_POST['description']) ) {        return new \WP_Error('empty_term_name', __('Tag description cannot be empty!', 'text-domain'));    } else {        return $term;    }}, -1, 2);

Here I used the built-in empty_term_name error to show notice message but you should register your own one.

Also, take a look at wp_ajax_add_tag to fully understand what we're doing.

Demo:

enter image description here


It's Ajax so you cannot rely on submit event, here is a solution, how you can do.

All you want to do is include form-required class to the parent tag of the particular element, but there is kick on it. their validateForm check only on input tags not on textarea so I have implemented an idea, it works.

Try this

function put_admin_script() { ?><script>    jQuery(document).ready(function(){        var description = jQuery('#tag-description');        if( !description ) {             description = jQuery('#description');         }           if( description ) {            description.after( $('<p style="visibility:hidden;" class="form-field form-required term-description-wrap"><input type="text" id="hidden-tag-desc" aria-required="true" value="" /></p>') );            }           description.keyup(function(){            $("#hidden-tag-desc").val( $(this).val() );         });        jQuery("#addtag #submit").click(function(){            console.log("Not empty"+description.val().trim().length);            if( description.val().trim().length < 1 ) {                description.css( "border", "solid 1px #dc3232" );            } else {                description.css( "border", "solid 1px #dddddd" );            }                           });     }); </script><?php }add_action('admin_footer','put_admin_script');