0

I have 10,000 custom posts relating to Marinas. Each marina has contact details in custom fields which include an email address and a contact name. I want to give each of those Marinas the ability to login and edit their details.

How do I create, either programmatically or by CSV import, user accounts for each Marina?

1 Answer 1

0

Here's an example that you could put into a script e.g. import.php inside the root of your WordPress install. We iterate over all marina posts (or whatever your CPT is) in batches of 50 (10,000 posts is far too much to load in one go), pull the contact details (you'll need ensure the field names are correct), then attempt to create a user.

<?php

require './wp-load.php';

set_time_limit( 0 );

$query = new WP_Query;
$paged = 1;

while ( true ) {
    $query->query([
        'posts_per_page' => 50,
        'post_type'      => 'marina',
        'paged'          => $paged,
    ]);

    if ( ! $query->have_posts() ) {
        break;
    }

    foreach ( $query->posts as $post ) {
        // Assumed meta fields, change to fit your needs
        $name  = trim( get_post_meta( $post->ID, 'name', true ) );
        $email = trim( get_post_meta( $post->ID, 'email', true ) );

        // Generate a unique username
        $login = $_login = sanitize_key( $name );
        $i     = 2;

        while ( ! $login || username_exists( $login ) ) {
            $login = "$_login-" . ++$i; 
        }

        // Name parts
        $name_parts = preg_split( '/ +/', $name );

        // Attempt to create the user
        $user_id = wp_insert_user([
            'user_pass'    => wp_generate_password(),
            'user_login'   => $login,
            'user_email'   => $email,
            'display_name' => $name,
            'first_name'   => array_shift( $name_parts ),
            'last_name'    => implode( ' ', $name_parts ),
            'role'         => 'subscriber',
        ]);

        if ( ! is_wp_error( $user_id ) ) {
            // do something with user ID?
        } else {
            // something went wrong
        }

        // Free up memory
        clean_post_cache( $post );
    }

    $paged++;
}

Disclaimer: This code is for demonstrative purposes only and I accept no liability for anything that might go wrong. I suggest you carefully examine it, ask any questions you might have, and when you're confident to run it, backup first!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.