wordpress.build

Javascript turned off in your browser!

You need to turn it on to use this site.

Custom WP-CLI Commands in WordPress | Create Your Own | Wp Build

Custom WP-CLI Commands in WordPress: How to Create Your Own

leo Cave 6 minute read AI, Code
WpBuild » Blog » Code » Custom WP-CLI Commands in WordPress: How to Create Your Own

Creating your own custom WP-CLI commands in WordPress may feel intimidating at first but it’s not much different than writing any other function in PHP. They can be incredibly powerful in both development and production environments, but with great power comes great responsibility.

What is the WP-CLI

For those who are unfamiliar; The WordPress Command Line Interface (WP-CLI) is a powerful tool that allows you to manage your WordPress websites directly through the command line. It provides a fast and efficient way to perform various tasks such as updating plugins, themes, and core, importing and exporting content, creating users, and much more. You can read more about it on the official WP-CLI website.

Activating and Using the WP-CLI

  1. To activate WP-CLI, you need to first install it on your server by following the installation instructions provided on the WP-CLI website.
  2. Once installed, you can start using WP-CLI by running commands in your terminal.
  3. You can explore all the available (out of the box) commands and their options on the official WordPress developer documentation.

Writing your own Custom WP-CLI Commands

Before you begin, as with most coding, breaking down your approach into manageable steps can make the process much easier to grasp.

Understand the Basics

Familiarise yourself with the existing commands and how they are structured. Start by exploring the WP-CLI documentation to learn about the various features and functionalities available to you as a developer.

Plan Your Command

Before writing any code, take the time to plan out your custom command. Determine what functionality you want it to have and how it will be implemented. Consider the arguments and options that your command will require, as well as any potential side effects or dependencies that need to be accounted for.

Write and Test, Test Test!

Once you have a clear plan in place, start writing your custom command using PHP. Test it thoroughly to ensure that it behaves as expected and handles various edge cases gracefully. Always add debugging to each key step of your function so you can clearly see where things might fail.

Diving Into a Real Use Case

So you have the WP-CLI installed, you have familiarised yourself with the basics, and now it’s time to do something useful with it!

Generate hundreds of Random WordPress Users with a custom WP-CLI command

I recently had to generate 100’s of random WordPress users for a membership site. Each random user needed to be assigned some meta values for QA testing various outputs and membership functions. The client also wanted the output to “look real” for other stakeholders – so no Lorem Ipsum or similar could be used in the user data.

This is where a custom WP-CLI command would do the job both elegantly and efficiently, with the help of a couple of API’s.

The Planning

  1. Find out what user meta needs to be populated for each user from the client.
  2. Find a ready-to-use API for creating sets of random user data. I ended up using https://randomuser.me that had a simple and effective API for the job.
  3. Use OpenAI’s API to generate realistic bios for each user based on a simple prompt.
  4. Add an optional argument to the WPCLI command to set the number of random users to create.

The WPCLI Command Function

Here’s a complete WP-CLI command function to generate realistic random users with metadata and avatars, leveraging the API’s.

 
if (defined('WP_CLI') && WP_CLI) {

    WP_CLI::add_command('generate_random_users', function($args, $assoc_args) {

        // Set a count argument for the command or default to 10
        $count = isset($args[0]) ? intval($args[0]) : 10;

        // Fetch random users from API (https://randomuser.me/documentation)
        $response = wp_remote_get('https://randomuser.me/api/?results={$count}&nat=us,gb,au,ca');

        // Check the request
        if (is_wp_error($response)) {
            WP_CLI::error("Failed to fetch random users.");
            return;
        }
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        // Check the results
        if (empty($data['results'])) {
            WP_CLI::error("No users returned from API.");
            return;
        }

        $created = 0;

        // Set up the loop
        foreach ($data['results'] as $user) {

			// Use OpenAI API to generate a short bio
			$openai_api_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; 
			$prompt = 'Add a prompt for generating the bio...';

			// Prepare the API request
			$response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
				'headers' =>; [
					'Content-Type'  => 'application/json',
					'Authorization' => 'Bearer ' . $openai_api_key,
				],
				'body' => json_encode([
					'model'    => 'gpt-3.5-turbo',
					'messages' => [
						['role' => 'user', 'content' => $prompt],
					],
					'max_tokens' => 120,
					'temperature' => 0.8,
				]),
				'timeout' => 30,
			]);
			$bio = '';
			if (!is_wp_error($response)) {
				$body = wp_remote_retrieve_body($response);
				$data = json_decode($body, true);
				if (!empty($data['choices'][0]['message']['content'])) {
					$bio = trim($data['choices'][0]['message']['content']);
				}
			}

	        // Prepare user data
            $first_name = ucfirst($user['name']['first']);
            $last_name = ucfirst($user['name']['last']);
            $email = strtolower($user['login']['username']) . '@example.com';
            $username = $email;
            $password = wp_generate_password(12, false);

            // Check if user exists
            if (username_exists($username) || email_exists($email)) {
                WP_CLI::log("User {$username} already exists, skipping.");
                continue;
            }

            // Create user
            $user_id = wp_create_user($username, $password, $email);
            if (is_wp_error($user_id)) {
                WP_CLI::log("Failed to create user {$username}: " . $user_id->get_error_message());
                continue;
            }
            // Check we are getting the picture URL
            if (empty($user['picture']['large'])) {
                WP_CLI::log("No picture available for user {$username}, skipping.");
                continue;
            }

            // Download and save the profile picture locally
            $image_url = esc_url_raw($user['picture']['large']);
            $tmp = download_url($image_url);

            if (is_wp_error($tmp)) {
                WP_CLI::log("Failed to download image for {$username}, skipping.");
                continue;
            }

            // Get the file name and type
            $file_array = array();
            $file_array['name'] = basename($image_url);
            $file_array['tmp_name'] = $tmp;

            // Check file type and upload to media library
            $attachment_id = media_handle_sideload($file_array, 0);

            // If error storing permanently, unlink temp file
            if (is_wp_error($attachment_id)) {
                @unlink($tmp);
                WP_CLI::log("Failed to sideload image for {$username}, skipping.");
                continue;
            }

            // Set user meta
            update_user_meta($user_id, 'first_name', $first_name);
            update_user_meta($user_id, 'last_name', $last_name);
            update_user_meta($user_id, 'nickname', $first_name);
            update_user_meta($user_id, 'terms_agreed', '1');
            update_user_meta($user_id, 'user_thumbnail', $attachment_id);
			update_user_meta($user_id, 'user_bio', $bio);

            // Set role
            $wp_user = new WP_User($user_id);
            $wp_user->set_role('subscriber');

            $created++;

            // Log the result
            WP_CLI::log("Created user: {$username} ({$first_name} {$last_name})");
        }

        WP_CLI::success("Created {$created} random users.");
    });
}

Command Line Usage

wp generate_random_users 100

Using this WP-CLI script will generate x100 users on your WordPress site. Doing this manually would have taken hours of laborious work. Obviously when using this WP-CLI function you will need your own OpenAI API key.

Need a WP-CLI Expert

Love WordPress and want to speed up your development using the WP-CLI, I can get you there. Get in touch! I am an experienced Freelance WordPress Developer.

Related posts

Got big ideas for your WordPress build?

I'm all ears! Get in touch and find out how I can turn your vision into a robust solution that delivers measurable results.