Good day! Is it possible in WordPress to limit the number of characters entered in the text field?

It is the input data. That is, that it was impossible to write more characters in the admin panel than specified.

This: enter image description here

  • Can. It is necessary to understand how you deduce it, this text. What types of posts is this. - KAGG Design
  • And how many symbols should be allowed and how / how are these actions made? - SeVlad
  • @SeVlad, did not quite understand the question. Suppose 300 characters. Shares are displayed as records, through a cycle, made using "register_post_type" - Igor
  • Simply if up to 250, it would be possible to use not a standard texarea, but text in an arbitrary field. This is so offhand .. - SeVlad
  • It is necessary that the context field be exactly in it, and not in another field. - Igor

2 answers 2

If simplified, it can be done like this:

add_filter( 'tiny_mce_before_init', 'my_content_limit' ); function my_content_limit( $initArray ) { $initArray['setup'] = <<<JS [function (editor) { editor.on('keydown', function( e ) { if (e.keyCode == 8 || e.keyCode == 46) { return; } var content = tinyMCE.activeEditor.getContent(); var max = 300; // Лимит на 300 символов var len = content.length; if (len >= max ) { alert( 'Вы ввели больше ' + max + ' символов!' ); tinyMCE.activeEditor.setContent(content.substr(0, max)); } }); }][0] JS; return $initArray; } 

Of course, you need to add a check on the record type, handle the insertion / deletion of text, etc. But the basic principle of this example demonstrates.

UPD: Still, it is strongly recommended to check the length of the string on the server side, as KAGG Design wrote in its answer .

  • Stunned !!! I did not know that you can create js right in functions !! Thank! - Igor
  • A curious decision. Plus)) - KAGG Design

Something like this should look like the code in functions.php

 add_filter('the_content', 'the_content_filter'); function the_content_filter( $content ){ global $post; $max_length = 30; if ( 'promo_post' === $post->post_type ) { $content = mb_substr( $content, 0, $max_length ); } return $content; } 

You need to know how your post type is registered - promo_post or otherwise.

  • I am sorry. You need a restriction on the input data. So that in the admin panel it was impossible to enter a value greater than indicated. - Igor