Ask Your Question
0

How can the WordPress post title be given a maxlength attribute?

asked 2022-01-09 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
0

answered 2021-04-25 07:00:00 +0000

djk gravatar image

To add a maxlength attribute to the WordPress post title, you can use the maxlength parameter of the wp_editor() function.

In your theme’s functions.php file, add the following code:

function custom_title_maxlength() {
    add_filter( 'tiny_mce_before_init', 'custom_tiny_mce_before_init' );
}
add_action( 'admin_head-post.php', 'custom_title_maxlength' );
add_action( 'admin_head-post-new.php', 'custom_title_maxlength' );

function custom_tiny_mce_before_init( $init ) {
    $init['setup'] = "function (ed) {
        ed.on('init', function() {
            var wpTitle = document.getElementById('title');
            if(wpTitle) {
                wpTitle.setAttribute('maxlength', '100');
            }
        });
    }";
    return $init;
}

This code uses the tiny_mce_before_init filter to add a JavaScript function to the setup parameter of the TinyMCE editor initialization. The function then adds a maxlength attribute to the post title input element with an ID of title.

Change the number 100 to the desired character limit.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-01-09 11:00:00 +0000

Seen: 20 times

Last updated: Apr 25 '21