I am trying to create a plugin that will generate users. I am pretty new to WordPress and my PHP is ehhhh. The idea for it is for the plugin to generate multiple users when its finished. Right now though I am just trying to get it to generate one. But I am having issues trying to do so, any ideas?
Once I click Submit, I get a ‘Settings Saved’. So, I believe that means the form went through but no user shows up in the DB. I imagine I am not getting the information in the form or executing my function properly.
<?php
function sl_add_options_page() {
// Add new page under the "Settings tab
add_options_page(
__( 'User Options' ),
__( 'User Options' ),
'manage_options',
'user_options_page',
'sl_render_options_page'
);
}
add_action( 'admin_menu', 'sl_add_options_page' );
function sl_render_options_page() {
?>
<div class="wrap">
<h2><?php _e( 'Content & User Generator Options' ); ?></h2>
<form action="options.php" method="post">
<?php settings_fields( 'num_users' ); ?>
<?php do_settings_sections( 'user_options_page' ); ?>
<p class="submit">
<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e( 'Submit' ); ?>">
</p>
</form>
</div>
<?php
}
function sl_add_setting() {
// Register a binary value called "pimple_disable"
register_setting(
'num_users',
'num_users',
'absint'
);
// Add the settings section to hold the interface
add_settings_section(
'user_main_settings',
__( 'User Controls' ),
'sl_render_main_settings_section',
'user_options_page'
);
// Add the settings field to define the interface
add_settings_field(
'user_main_settings_field',
__( 'How Many users' ),
'sl_render_users_input',
'user_options_page',
'user_main_settings',
'sl_wp_create_user'
);
}
add_action( 'admin_init', 'sl_add_setting' );
function sl_wp_create_user($username, $password, $email) {
$num_users = intval( $_GET['num_users'] );
$username = 'Testing';
$email = 'fakeemail@easyfakemail.com';
$password = wp_generate_password( 12, false );
for( $j = 0; $j < $num_users; $j++ ) {
$user_login = esc_sql( $username );
$user_email = esc_sql( $email );
$user_pass = $password;
$userdata = compact('user_login', 'user_email', 'user_pass');
return wp_insert_user($userdata);
}
echo '<div id="message" class="updated fade"><p><strong>' . $num_users . ' Users created</strong></p></div>';
}
function sl_render_main_settings_section() {
echo '<p>Main settings for the Content and User Generator plugin.</p>';
}
function sl_render_users_input() {
echo '<input id="num_users" name="num_users" type="input" value="" />';
}
You are using
add_settings_field
wrong: the functionsl_wp_create_user
is being passed as$args
(and you probably don’t need any args), and it should be the sanitize callback forregister_settings
.Make the input like:
And the sanitize function: