Select theme while registering in wordpress multisite network

In this article we will take a look on how we can select theme while registering in  wordpress multisite network. No doubt users can do so after registration from admin panel, here we will explore how to do the same during registration itself.

Select theme while registering in wordpress multisite network

The overall process comprises of 3 steps

  1. Get a list of all the installed and active themes in wordpress installation.
  2. Add a custom field in user registration form with a list of all the available themes.
  3. Save the selected theme in database.
<?php
/**
 * Add custom field to registration form
 */
add_action( 'signup_blogform', 'aoc_show_addtional_fields' );
add_action( 'user_register', 'aoc_register_extra_fields' );

function aoc_show_addtional_fields() 
{
    $themes = wp_get_themes();
    echo '<label>Choose template for your site';
    foreach ($themes as $theme){
        echo '<img src="'.$theme->get_screenshot().'" width="240"/>';
        echo $theme->name . ' <input id="template" type="radio" tabindex="30" size="25" value="'.$theme->template.'" name="template" />';
    }
    echo '</label>';
}

function aoc_register_extra_fields ( $user_id, $password = "", $meta = array() ) {
    update_user_meta( $user_id, 'template', $_POST['template'] );
}

// The value submitted in our custom input field needs to be added to meta array as the user might not be created yet.
add_filter('add_signup_meta', 'aoc_append_extra_field_as_meta');
function aoc_append_extra_field_as_meta($meta) 
{
    if(isset($_REQUEST['template'])) {
        $meta['template'] = $_REQUEST['template'];
    }
    return $meta;
}

// Once the new site added by registered user is created and activated by user after email verification, update the template selected by user in database.
add_action('wpmu_new_blog', 'aoc_extra_field', 10, 6);
function aoc_extra_field($blog_id, $user_id, $domain, $path, $site_id, $meta) 
{
    update_blog_option($blog_id, 'template', $meta['template']);
    update_blog_option($blog_id, 'stylesheet', $meta['template']);
}
?>

The above script can be pasted in functions.php file.