Order comment fields by importance: textarea first

I like feedback on my work. Even “You are wrong, because …” is better than silence. That’s why I try to keep my readers in the flow. Nothing should interrupt the process of interaction. But by default, WordPress will set the name and email fields between a blog post and the comment textarea.

Let’s see how we can fix that.

The precondition for the following code: the theme is using the function comment_form() and not a completely hand rolled comment form.

There are two important hooks we can use:

  1. The filter comment_form_defaults is an array of default fields and labels, among them the key comment_field for the textarea and its label.
  2. The action comment_form_top is just an opportunity to print extra content into the comment form.

We use the first hook to replace the textarea with an empty string. Removing the key would result in an error, because WordPress doesn’t check if it was removed. We store the original content in a static variable in our function.

When the second hook is called we print the textarea. It will be on top of the other fields now. The static variable allows us to re-use the same callback function.

add_filter( 'comment_form_defaults', 't5_move_textarea', 100 );
add_action( 'comment_form_top',      't5_move_textarea' );

/**
 * Take the textarea code out of the default fields and print it on top.
 *
 * @wp-hook comment_form_defaults 100
 * @wp-hook comment_form_top
 * @param   array $input Default fields if called as filter
 * @return  string|void
 */
function t5_move_textarea( $input = array () )
{
    static $textarea = '';

    if ( 'comment_form_defaults' === current_filter() )
    {
        // Copy the field to our internal variable …
        $textarea               = $input['comment_field'];
        // … and remove it from the defaults array.
        $input['comment_field'] = '';
        return $input;
    }

    // Now called on comment_form_top, $textarea is filled.
    print apply_filters( 'comment_form_field_comment', $textarea );
}

And that’s all. You can download it as a plugin from GitHub.

This article is based on an answer I have written on WordPress Stack Exchange.

Author:

Web developer since 1998, moderator on WordPress Stack Exchange, author, manic reader.

Code is my drug.

Find Thomas Scholz on toscho.de⁠, ⁠, ⁠, ⁠, ⁠, ⁠, and .

1 Comment

One pingback

  1. Almost* all wordpress themes suck at comment form design | mark kaplun's blog

Leave a Reply

Your email address will not be published.