Whether you’re batch-updating user profiles, triggering imports, or just debugging your code, writing your own Drush commands is one of the most underrated power moves in Drupal development. And the best part? It’s easier than you think.
In this guide, you’ll learn how to build a custom Drush command from scratch — using modern Drupal practices — and start bending your site to your will, one command at a time.
Why use Custom Drush Commands
Custom Drush commands are extremely useful for automating and simplifying tasks. Some common scenarios where custom Drush commands come in handy include:
- Automating site maintenance: Tasks like clearing cache, updating fields, or resetting users.
- Batch processing: Handling large imports, exports, or content migrations.
- Triggering specific workflows: Running batch jobs or cron-like operations.
- Interacting with Drupal entities: Updating or managing content programmatically.
Drush commands provide developers with an easy way to automate processes, reduce the need for UI navigation, and even manage remote sites via the command line.
Our goal in this project is to create a Drush command that will set the preferred custom language of users of a specified role.
Great! Let's break down the goal of creating a Drush command.
Problem Breakdown:
- We need a custom Drush command.
- The command will set the preferred language for users that belong to a certain role (e.g., "editor", "admin").
- This custom language will be set on a per-user basis.
Plan:
- Create a Drush command that takes a user role and language code as parameters.
- The command will then find all users with that role.
- For each user, the command will set the preferred language to the provided language code.
Development
Step 1: Create your custom module
First, you need a custom module to hold your Drush commands.
- Create the custom_drush_language.info.yml file:
name: 'Custom Drush Language Setter'
type: module
description: 'Set preferred custom language for users based on their role.'
core_version_requirement: ^10
package: Custom
dependencies:
- drush/drush
Step 2: Enable the custom module
You may do so by Drupal UI under Admin > Extend > Install New Module or by running the following command
drush en custom_drush_language
Step 3: Define the Drush Command
Now, let’s create the Drush command itself. This will be responsible for setting the preferred language for users who belong to a particular role. Create this file under your custom module folder: custom_drush_language > src > Commands
<?php
namespace Drupal\custom_drush_language\Drush;
use Drush\Commands\DrushCommands;
use Drupal\user\Entity\User;
use Drupal\Core\Language\LanguageInterface;
/**
* Drush command to set preferred language for users with specific roles.
*/
class CustomLanguageDrushCommands extends DrushCommands {
/**
* Set preferred language for users with a specific role.
* @command user:setlang
* @aliases user-lang
*
* @option role
* The type of user role
* @default role 'authenticated'
*
*
* @option lang
* The language code
* @default lang 'en'
*
*/
public function setLanguageForRole($options = ['role' => NULL, 'lang' => NULL]): void {
// Load users by role.
$query = \Drupal::entityQuery('user')->accessCheck(TRUE)->condition('roles', $options['role']);
$user_ids = $query->execute();
$users = User::loadMultiple($user_ids );
// If no users found with the role
if (empty($users)) {
$this->output()->writeln("<error>No users found with the role '$role'.</error>");
\Drupal::logger('user_langcode')->warning("No users found with the role {$role}");
return;
}
$langcode = $options['lang'];
// Loop through each user and set the preferred language
foreach ($users as $user) {
// Ensure the language code is valid
if (\Drupal::languageManager()->getLanguage($langcode)) {
$user->set('preferred_langcode', $langcode);
$user->save();
\Drupal::logger('user_langcode')->info("User {$user->getUsername()}'s language set to {$langcode}");
} else {
\Drupal::logger('user_langcode')->warning("Invalid language code: {$langcode}");
}
}
}
}
Step 4: Run the Command
After creating your Drush command, don't forget to clear the cache: drush cr
.
You can now run your custom Drush command. For example, to set the language for all users with the editor
role to fr
(French):
drush user:setlang --role=editor --lang=fr
Conclusion
You now have a custom Drush command that sets the preferred language for users based on their role. This is an effective way to automate language assignments for different groups of users, improving site management and user experience.
Feel free to extend this further by adding additional features, such as support for multiple roles or validation checks for more advanced language settings.
Enjoy creating your custom command!