+353 (0)22 55002 info@spiralli.ie

Autopopulating New User Data In WordPress

We’re currently implementing a large application based on WordPress, where the built in WordPress user functionality is supplemented with extra fields which identify the user uniquely. We don’t really need the username and email fields that much, but they are core to the WordPress users system. We chose to hide them and autopopulate them, rather than try to remove them completely. I just wanted to share the code to do it, as it’s really simple.

I could have created a simple plugin to do the job, but I chose to add the code to the theme’s functions.php for now. All I’m doing here is checking if the we are on the admin page user-new.php, and if so adding a javascript file with the wp_enqueue_script function:

[code]
function sp_autopopulate($hook) {
if ( ‘user-new.php’ != $hook ) {
return;
}
wp_enqueue_script( ‘autopopulate’, site_url() . ‘/autopopulate.js’ );
}
add_action( ‘admin_enqueue_scripts’, ‘sp_autopopulate’ );
[/code]

Next comes the javascript. It’s only 3 lines. It takes the UNIX datestamp (number of seconds since Jan 01 1970) which is a simple way of getting a unique value, and uses it to populate the username and email address ( with @test.com appended to put it in valid email address format)

[code]
jQuery(document).ready(function($) {
unixstamp=Date.now();
document.getElementById(‘user_login’).value=unixstamp;
document.getElementById(’email’).value=unixstamp+’@test.com’;
})
[/code]

Perhaps someone, somewhere will find the code useful. It can be adapted to work with any of the other fields on the add user page.