Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add maxlength attribute to WordPress post title

Is there a hook I can use to append a maxlength attribute to WordPress post titles? I am familiar with sub string function techniques (e.g. http://www.doc4design.com/articles/wordpress-5ways-shorten-titles/), but that's not the same. I've also seen the Limit Post Titles plugin which again works well, but still doesn't enforce the limit.

I want to limit the character length from the onset, e.g.:

<input type="text" autocomplete="off" spellcheck="true" id="title" value="" size="30" maxlength="60" name="post_title" />

Having not found anything on this subject, I assume there might be reasoning as to why this is not a good idea? If so, I would be interested in knowing why.

like image 725
Michel Joanisse Avatar asked Jan 30 '26 02:01

Michel Joanisse


1 Answers

From looking at the code, I don't think there is a filter you can hook into the add a maxlength attribute to the title field.

You could use javascript to add the attribute:

add_action('admin_footer', function() {
?>
    <script>jQuery('input#title').attr('maxlength', 60);</script>
<?php
});

Note that if you really need to enforce the limit, the maxlength attribute is not sufficient. It's trivial to bypass the restriction.

You'll also need to use the save_post action to validate the title.

I assume there might be reasoning as to why this is not a good idea

It is a good idea to enforce restrictions in the frontend. Letting the user know that their input does not fall within an expected range prior to submitting a form is generally preferable to giving them an error message after submitting the form. You just have to bear in mind that those restrictions must be verified in the backend.

like image 185
Mathew Tinsley Avatar answered Feb 01 '26 18:02

Mathew Tinsley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!