//Hacking the WordPress comment form

Filed under Code

Tagged: ,

In the pursuit of a decent comment form for my blog I’ve tried at least 5 different form plugins over the years but my favourite solution is always going to be to use the wordpress comments form.

The comment form makes sense to me because:

  • it is protected by akismet;
  • generally you only need the name, email and comment field;
  • All your form responses are emailed to you and a record is kept in your database.

How do you do it?

I’m assuming a general knowledge of wordpress templates here so let me know in the comments of you want further clarification. After looking through the file wp_comments_post.php I noticed that it looks for a post parameter called ‘redirect_to’ that isn’t present in the regular comment form. I added the following hidden field to a copy of the comments form I made on a custom page template:

<input type="hidden" name="redirect_to" value="/contact?success" />

The end result is that a form submission will return to my contact page but with the added query string in the URL. I then check for the query string in the template using PHP to show a thank you message in place of the form.

<?php if ( isset($_GET['success']) ) { ?>

   ... show thank you message ...

<?php } else { ?>

   ... show comment form ...

<?php } ?>

There are some caveats to this approach:

  • No real error handling as the comments list isn’t written out so javascript validation is required.
  • If you are displaying recent comments you will need to block ‘comments’ made on the contact page from showing up.

Those problems may be deal breakers for you – especially the error handling but until I find (or write) the prefect contact form plugin this is the approach that works for me.

One Response to Hacking the WordPress comment form

  1. You’re right, using the built in comment system is the way to go (spam filtering especially).

    As for a contact page, in WordPress it’s easier to just add a second template for your contact page, one that doesn’t include the second half of the comment template (just the form, no recent comments listing). And validation is best done client-side anyway as WordPress’s validation is after POSTing, which is a kick in the gonads of usability.

Leave a Reply