I have a form were users can post question on my page and I would like to limit the characters in the description part of the form. It would also be a plus if I could get a word counter to work.

The form:

            <p><label for="title">Titel</label><br />
            <input type="text" id="title" value="" tabindex="1" size="20" name="title2" />

            <p><?php wp_dropdown_categories( 'show_option_none=Kategorier&tab_index=4&taxonomy=register_vote_category&hide_empty=0' ); ?></p>

            <p><label for="description">Beskrivning</label><br />
            <textarea id="description" tabindex="3" name="description2" cols="50" rows="6"></textarea>

            <p><input type="submit" value="Skicka" tabindex="6" id="submit" name="submit2" /></p>

            <input type="hidden" name="action" value="new_post" />
            <?php wp_nonce_field( 'new-post' ); ?>

The php:

if(isset($_POST['submit2'])) {

            $title = $_POST['title2'];
            $description = $_POST['description2'];

            if(strlen($title) <= 0 || strlen($description) <= 0){

                echo wpautop( 'Du måste skriva i både titel och beskrivning' );

            else if (strlen($title) >= 1 && strlen($description) >= 1) {

            $new_post = array(
                'post_title'    => $title,
                'post_content'  => $description,
                'post_category' => array($_POST['cat']),  // Usable for custom taxonomies too
                'post_status'   => 'publish',           // Choose: publish, preview, future, draft, etc.
                'post_type' => 'category-vote'  //'post',page' or use a custom post type if you want to
            //save the new post
            $pid = wp_insert_post($new_post); 
            //insert taxonomies

To limit characters add this to your textarea: maxlength="200" changing "200" to whatever you want the character limit to be.

<textarea id="description" maxlength="200" tabindex="3" name="description2" cols="50" rows="6"></textarea>

For a character counter you will need some basic Javascript, something like this:

counter = function() {
    var value = $('#description').val();

    if (value.length == 0) {

    var totalChars = value.length;

    $('#totalChars').html(totalChars); //change the selector to whatever the ID of your counter area is

$(document).ready(function() {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.