Add checkbox with label to a form For a WordPress login form I have written a small plugin. It adds a checkbox with a unique name to the form and if that name is not present in the login POST request it just dies.

The idea is preventing scripted attacks made for regular WordPress login forms.

The PHP code is okay (imho), but I think the JavaScript code looks rather … inelegant. Everything works as expected, it is just not beautiful. What could I improve?

&lt;?php  # -*- coding: utf-8 -*-
/**
 * Plugin Name: T5 Unique Log-in Field
 * Description: Adds a checkbox with a unique name to the login form to prevent scripted log-in attempts.
 * Plugin URI:
 * Version:     2013.04.14
 * Author:      Thomas Scholz
 * Author URI:  http://toscho.de
 * Licence:     MIT
 * License URI: http://opensource.org/licenses/MIT
 */

add_action( 'login_init',   't5_unique_login_field' );
add_action( 'login_footer', 't5_unique_login_field' );

/**
 * Add a checkbox with a unique name to the login form.
 *
 * @wp-hook login_init
 * @wp-hook login_footer
 * @return  void
 */
function t5_unique_login_field()
{
    if ( ! empty ( $GLOBALS['interim_login'] ) )
        return;

    if ( defined( 'LOGGED_IN_SALT' ) )
        $salt = constant( 'LOGGED_IN_SALT' );
    else
        $salt = filemtime( __FILE__ );

    $unique = md5( $_SERVER[ 'HTTP_HOST' ] . $salt );

    if ( 'POST' === $_SERVER[ 'REQUEST_METHOD' ] )
    {
        if ( ! isset ( $_POST[ 'log' ] ) )
            return;

        if ( empty ( $_POST[ $unique ] )
            or 'on' !== strtolower( $_POST[ $unique ] )
        )
            exit;

        return;
    }

    ?&gt;
&lt;script&gt;
var unique    = '&lt;?php echo $unique; ?&gt;',
    checkBox  = document.createElement( 'input' ),
    paragraph = document.createElement( 'p' ),
    label     = document.createElement( 'label' ),
    labelText = document.createTextNode( ' I am human' );

checkBox.setAttribute( 'name', unique );
checkBox.setAttribute( 'type', 'checkbox' );
checkBox.setAttribute( 'id',   unique + '_id' );

label.setAttribute( 'for', unique + '_id' );
label.appendChild( checkBox );
label.appendChild( labelText );

paragraph.appendChild( label );
paragraph.setAttribute( 'style', 'clear:both;float:none' );
// get the same font style as the last checkbox
paragraph.setAttribute( 'class', 'forgetmenot' );

document.getElementById( 'loginform' ).appendChild( paragraph );
&lt;/script&gt;
&lt;?php
}


Screenshots: 

Before plugin activation



After plugin activation
This is not meant to be a comprehensive answer:

If you do not want a bug that happens only in some browsers and only some of the time, use a safe, conservative format as an id

checkBox.setAttribute( 'id',   unique + '_id' );


If id is a random 64-bit integer or a GUID in the following form (b362e877-95c3-4e88-99dc-ceb4600639b5), then you would want id to be 'id_' + unique instead of unique + '_id'