Auto-Create Wallets for New & Existing Users with Unique Titles V1

PHP

Difficulty Level: intermediate

Snippet Description

This snippet automatically creates a Wallet CPT (wallets) for every WordPress user.

  • New Users: Wallets are created automatically when a user registers.

  • Existing Users: Wallets are generated in batches for all existing users who don’t already have one.

  • Unique Titles: Each wallet gets a unique alphanumeric suffix (e.g., John Wallet-A3F7) to prevent collisions.

  • Safe for Large Sites: Batch processing ensures it works without memory or timeout issues.

  • Default Meta Values: All wallets start with balances set to 0 and timestamps for creation and updates.

This MU-Plugin is production-safe, requires no dependencies, and works with WooCommerce, JetFormBuilder, or default WordPress registration.

<?php
/*
Plugin Name: Auto Create Wallets for Users
Description: Automatically creates Wallet CPTs (wallets) for new users and existing users in batches, with unique alphanumeric titles.
Version: 1.0
Author: Your Name
*/

// -------------------------------
// 1. Create wallet for new users
// -------------------------------
add_action('user_register', 'auto_create_wallet_for_user', 20, 1);
function auto_create_wallet_for_user($user_id) {
    create_wallet_if_not_exists($user_id);
}

// ---------------------------------------------------
// 2. Batch-create wallets for existing users safely
// ---------------------------------------------------
// Run only on admin init
add_action('admin_init', 'create_wallets_for_existing_users_batch');
function create_wallets_for_existing_users_batch() {

    // Run once per site load
    if (get_option('wallets_batch_done')) {
        return;
    }

    $batch_size = 50; // Number of users to process at once
    $offset = 0;

    do {
        $users = get_users([
            'number' => $batch_size,
            'offset' => $offset,
            'fields' => ['ID'],
        ]);

        if (empty($users)) {
            break;
        }

        foreach ($users as $user) {
            create_wallet_if_not_exists($user->ID);
        }

        $offset += $batch_size;
    } while (!empty($users));

    // Mark batch as done
    update_option('wallets_batch_done', 1);
}

// -----------------------------------------
// 3. Helper function to create wallet
// -----------------------------------------
function create_wallet_if_not_exists($user_id) {

    // Check if wallet exists
    $existing = get_posts([
        'post_type'  => 'wallets',
        'meta_key'   => 'user_id',
        'meta_value' => $user_id,
        'post_status'=> 'any',
        'numberposts'=> 1,
    ]);

    if (!empty($existing)) {
        return; // Wallet already exists
    }

    // Get user
    $user = get_userdata($user_id);
    $username = $user->display_name ?: $user->user_login;

    // Generate unique alphanumeric suffix (4 chars)
    $suffix = strtoupper(substr(md5(uniqid('', true)), 0, 4));

    // Create wallet CPT
    $wallet_id = wp_insert_post([
        'post_type'   => 'wallets',
        'post_status' => 'publish',
        'post_title'  => $username . ' Wallet-' . $suffix,
    ]);

    // Set default wallet values
    if ($wallet_id) {
        update_post_meta($wallet_id, 'user_id', $user_id);
        update_post_meta($wallet_id, 'available_balance', 0);
        update_post_meta($wallet_id, 'pending_balance', 0);
        update_post_meta($wallet_id, 'total_withdrawn', 0);
        update_post_meta($wallet_id, 'total_earned', 0);
        update_post_meta($wallet_id, 'created_at', current_time('mysql'));
        update_post_meta($wallet_id, 'updated_at', current_time('mysql'));
    }
}

How the Code is Implemented:

  1. Create MU-Plugin File

    File path:

    wp-content/mu-plugins/auto-create-wallet.php
    

  2. Paste the Code
    Copy the entire PHP snippet into the file.

  3. New User Wallet Creation
    Uses the user_register hook to automatically create a wallet when a new user registers.

  4. Existing User Wallet Creation
    Runs once on admin_init for admins.
    Processes users in batches of 50 to prevent memory or timeout issues.|
    Only creates wallets for users who don’t already have one.

  5. Wallet Post Title
    Combines the username with a unique 4-character alphanumeric suffix:

    John Wallet-A3F7
    Jane Wallet-7B2C
    

  6. Default Meta Fields

    • user_id → links wallet to the user

    • available_balance, pending_balance, total_withdrawn, total_earned → all set to 0

    • created_at and updated_at → current timestamp

      Once-off Execution

      • After existing wallets are created, the batch process does not run again.

Usage Instructions

  1. Create MU-Plugin File

    • Path: wp-content/mu-plugins/auto-create-wallet.php

  2. Paste the Code

    • Copy the full PHP snippet into the file.

  3. Trigger Existing User Wallets

    • Log in as an admin once; wallets for existing users will be created automatically in batches.

  4. New User Wallets

    • Any new registered user will automatically get a wallet.

  5. Optional:

    • After existing wallets are created, the batch process won’t run again.

    • You can remove/comment the batch code if desired.

Table of Contents