chipcullen.com

web designer + front-end developer

Altering the comment form in WordPress

Posted on by Chip Cullen

Intro

Recently a client wanted to change the comment form on a WordPress site I was building for them. Specifically, they just wanted to have a Name field and the Comment field – omitting the E-mail and Website fields. They also wanted their labels to have particular wording.

I had never done this before, and after a lot of googling, I figured it out. I didn’t feel that a lot of the tutorials out there provided enough information, so I’m hoping to rectify that problem with this post.

Assumptions

I’m going to assume that you are a developer type who is setting up a WordPress site. These techniques work on WordPress version 3 and up. In my examples, though, I’ll be writing to the current release at the time of this post – 3.3.1. I am going to assume that you are familiar with how a theme is constructed, and that you aren’t scared by a little PHP. It’s really not that bad.

What I’m not going to cover

I’m not going to go into how to add pieces to the comment form that aren’t already there – e.g. adding another field or button. That involves intercepting the form and making sure the database can handle it – and frankly is above my head at the moment.

Context

These techniques all involve files that are found in your theme. While you could hack WordPress core, that is highly inadvisable. Every time you updated your WordPress install, you’d have to redo your changes.

I’m going to discuss two techniques, and each affects a particular file. The first technique involves comments.php, which is found in most themes. A theme doesn’t necessarily have a comments.php file, but it is generally considered best practice to do so.

The second technique involves changes to functions.php, which again is found in most themes. Any real logic that happens in your theme tends to be found in a theme’s functions.php.

Brief historical interlude

The comment form in WordPress used to be a fairly straightforward affair, but a messy one. Previous to version 3, the entire comment form, markup and everything, lived in a theme’s comments.php file. While this made it a snap to alter the comment form, it resulted in a big hairy ball of code living in a theme.

In WordPress 3, there was an effort to abstract this functionality, resulting in one simple call that would be needed in your theme:

<?php comment_form(); ?>

This one line will produce the comment form that we all know and love. Which is, ultimately, a good thing. 96.429% of WordPress sites out there (I asked) use the default comment form. There is no reason to have that big mess living in the theme of the vast majority of sites.

However, if you do want to alter the comment form, it’s now a little more tricky than simply locating the markup you want to change.

A tale of two methods

There are two ways to go about altering your comment form, as I’ve mentioned. Which method you choose depends on what you want to accomplish.

Please note: Method 2 will trump Method 1, so choose wisely

Method 1: Altering the comment_form() call in comments.php

This method is good for

  • Altering all of the details about the comment form
  • Changing the markup of the fields, including labels

This method basically entails taking the normal comment form call:

<?php comment_form(); ?>

And expanding it with new details about how you want the form to be generated. If you want to change some of the details, you need to specify those changes with an array that will be the argument for the function. Like so:

<?php comment_form(array()); >

You put your changes in that array:

<?php comment_form(array(
        'parameter_name' => 'value',
        'another_parameter' => 'value'
    ));
?>

What parameters can you set? Pretty much anything to do with the comment form. Take a look at the WordPress Codex entry on comment_form(), which gives you a run down of the parameters that you can set, and their default values (which WordPress will use unless you specify otherwise).

Want to change the explanatory text after the comment field to have a link to a privacy policy, instead of the list of allowed HTML? No problem:

<?php comment_form(array(
        'comment_notes_after' => '<p>Please see our <a href="privacy.html">privacy policy</a>.</p>'
    ));
?>

If you need to set more than one parameter, but sure to include a comma at the end of each parameter, except the last one.

If you want to change the fields of the comment form, that takes a little bit more effort. You will need to create a fields array (I’m going to call it $fields) within the array you just created, and that second array will be called by the ‘fields’ parameter. So we will start out with that new array:

<?php comment_form(array(
        $fields = array(
            'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Your Name' ) . '</label><input id="author" name="author" type="text"  value="Your First and Last Name" size="30"' . $aria_req . ' /></p>'
            );
    ));
?>  

This has redefined how I want the “author” field to be generated. In this case, I’ve changed the label text to say “Your Name” and the initial value of the field itself. Now I need to call that field within the parameters:

<?php comment_form(array(
        $fields = array(
            'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Your Name' ) . '</label><input id="author" name="author" type="text"  value="Your First and Last Name" size="30"' . $aria_req . ' /></p>'
            );

        'fields'                => apply_filters( 'comment_form_default_fields', $fields ), 
        'comment_notes_after'   => '<p>Please see our <a href="privacy.html">privacy policy</a>.</p>'   
    ));
?>

This piece:

apply_filters( 'comment_form_default_fields',

Tells WordPress you’re going to change the fields of the comment form, then, you just supply in the name of your array ($fields, in this case). You can change each of the fields using this array technique – author, email, website and comment.

This whole comment_form() function now goes in your comments.php file at the point where you want the comment form to appear – which is usually after the listing of existing comments.

Method 2: Using filters in functions.php

This method is good for

  • Omitting or changing fields
  • If you want the nuclear option, and never want to hear from those fields again

The second method employs WordPress filters. Using a filter, you can override the comment form before final output.

You will want to add this filter to your theme’s functions.php – which most themes will have. If your theme doesn’t have a functions.php file, simply create one and make sure it opens with

<?php 

Next you will want to create a function that defines your changes. As far as I’m aware, you can only modify the fields of the comment form with this method. This is an example function:

function alter_comment_form_fields($fields){
    $fields['email'] = '';  //removes email field
    $fields['url'] = '';  //removes website field
    return $fields;
}

The name of the function can be whatever you want – it will be called later. This example function will remove the email and website fields from the comment form. Want to change the author field as well?

function alter_comment_form_fields($fields){
    $fields['author'] = '<p class="comment-form-author">' . '<label for="author">' . __( 'Your name, please' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
                    '<input id="author" name="author" type="text" placeholder="John Smith" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>';
    $fields['email'] = '';  //removes email field
    $fields['url'] = '';  //removes website field

    return $fields;
}

Keep in mind that if you want to modify a field, you have to include everything that is part of the field – label and input. In this example, I’m changing the label to say “Your name, please”, and I’m modifying the input to have a placeholder attribute.

Okay, you’ve made the modifications, now you have to call this function. You do that with a filter – in this case, one that WordPress has built in and understands – it’s called “comment_form_default_fields”:

function alter_comment_form_fields($fields){
    $fields['author'] = '<p class="comment-form-author">' . '<label for="author">' . __( 'Your name, please' ) . '</label> ' . ( $req ? '<span class="required">*</span>' : '' ) .
                    '<input id="author" name="author" type="text" placeholder="John Smith" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></p>';
    $fields['email'] = '';  //removes email field
    $fields['url'] = '';  //removes website field
    return $fields;
}

add_filter('comment_form_default_fields','alter_comment_form_fields');

So you take that function and filter call, put it in your functions.php file, and give it a whirl. This won’t affect where on the page your comment form appears, but rather the fields within it. The placement of the form is still controlled by your comments.php file, and where you put the comment_form() call.

Again, bear in mind that the filter method will override whatever you do in comments.php.

As an aside, I like to keep this snippet around so I can drop any of the fields quickly -

function alter_comment_form_fields($fields){
    //$fields['author'] = ''; //removes name field
    //$fields['email'] = '';  //removes email field
    //$fields['url'] = '';  //removes website field
    return $fields;
}

add_filter('comment_form_default_fields','alter_comment_form_fields');

Just put that in your functions.php and uncomment the line with the field you want to omit. Boom. Done.

Conclusion

I hope this post will help you make changes to your WordPress comment form. I’ve tried to be comprehensive and provide context, so sorry it’s a little long. If you use these techniques – I’d love to hear about it in the comments.

This entry was posted in Wordpress and tagged , . Bookmark the permalink.

17 Responses to Altering the comment form in WordPress

  1. Can I apply a filter in my child theme? I would like to remove the website-field from my guestbook. Is the right action then to make a functions.php in my child theme and put the following into it (I use the twentyeleven child theme):

    <?php function alter_comment_form_fields($fields){ //$fields['url'] = ”; //removes website field return $fields; }

    add_filter(‘comment_form_default_fields’,’alter_comment_form_fields’);

  2. sunil says:

    I hate this function with a passion.

    You can’t change the names of the ID’s and classes. You get very limited control over the markup and in order to exert control over the fields you have to write horrible mixed up php and html, with convoluted and confusing quoting.

    It’s a mess created by shortsighted developers.

    • Chip Cullen says:

      As someone who was used to the comment form pre-WordPress 3, I agree, the ‘new way’ is very confusing, and more complicated than it needs to be. It used to be very approachable, and now it’s not. And you’re right, it does actually limit you in terms of markup control (on the form element itself).

      I guess it’s a matter of use-case. I think the WP developers looked at what was needed for the vast majority of users out there – which, really, is the standard form. Also, by abstracting certains parts out, it ensures that the form will still properly function even if certain parts are changed.

  3. Pingback: Wordpress and the comment_form() function |

  4. Pingback: Reduce Spam Comments

  5. GiorgioC says:

    Hi, is possibile to have one specific comment ever first, and user comment last?

    • Chip Cullen says:

      If it is, I don’t know how to do it. Sorry!

      There may be some way to manipulate the core comment function (which acts much like any other Loop) to look for a particular comment ID, but I don’t know for sure. Plus, this would mean custom code for every comment you wanted to treat like that. Maybe there might be a plugin for that?

  6. Theo says:

    Hello Chip,

    Maybe you can help me with this. I am working with WordPress 3.5.2 twentyeleven theme and I am trying to change the labels into Spanish with your method above. I introduced the following code into the comments.php file but nothing happens and everything remains the same. I don’t know what I am doing wrong. Could you help me please? Thanks

    ‘Deja su comentario’, ‘comment_notes_before’ => ‘Su email no se publica, ni se comparte ni se vende.’, ‘comment_notes_after’ => ‘No se admite HTML.’, ‘label_submit’ => ‘Enviar Comentario’, )); ?>

    • Chip Cullen says:

      Theo – It’s hard to say – I think your comment code may have been mangled a little by my comment form. I think there is more to your function then came across through my form.

      Roughly, what you have should look like:

      <?php comment_form(array(
              'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Deja su comentario’, 'noun' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea></p>'
              'comment_notes_before’ => ‘Su email no se publica, ni se comparte ni se vende.’, 
              'comment_notes_after'   => '<p>No se admite HTML.</p>',
              ‘label_submit’ => ‘Enviar Comentario’
          ));
      ?>
      

      Note that in your code, you had a comma after the last parameter. PHP can be very picky about those things – the last parameter in an array should not have a comma (JavaScript, on the other hand, is more forgiving on things like that).

      • Theo says:

        Hello Chip Thanks. I copied the code directly into the comment.php file and it didn’t work. I passed the code through dreamweaver and I found out that there were some apostrophs that had changed for a different one. I arranged this and copied and pasted the code again into the content.php file and also no result. Nothing even changes on the page. I am now wondering if I am pasting it in the right location. I did it two ways: 1. just replaced the php comment_form(); code. 2. I replaced the same as in 1 but also deleted all the other code between the #comments div tags. Do you have any idea what it can be?

        • Chip Cullen says:

          Theo – At this point, I’m not sure I can do much more without looking directly at your theme. However, if you are deleting that much code, and not seeing any change in your page -at all- I think you’re not working in the right spot. Are you hacking twentyeleven directly, or working in a child theme? Are you double sure that the theme you are working on is the one that is activated?

  7. Burak says:

    Hi,

    My codes are exactly same your example. WP_Debug find some bugs. I searched google and find your blog post.

    It gives “Uninitialized string offset: 0″ error… $fields['author'] and other $fields…

    Form works correctly but i need to fix wp_debug errors. Do you have an idea?

    • Chip Cullen says:

      Burak,

      Yikes- that sounds tough. Unfortunately, I don’t have any ideas off the top of my head. Just by searching around the internet, it looks like that error crops up around issues to do with Thumbnails, not comment forms – but that doesn’t necessarily rule out your issue. When you remove this code, does your error go away? That is to say, does it only show up when you alter the comment form?

      • Burak says:

        It’s important for me.

        I found.

        function alter_comment_form_fields(){ $commenter = wp_get_current_commenter(); $req = get_option( 'require_name_email' ); $aria_req = ( $req ? " aria-required='true'" : '' );

        //bla bla bla some codes

  8. Pingback: lockjs

  9. Pingback: Reduce Spam Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>