Are you a command-line freak like me? Do you want to create some custom WP-CLI commands? If you’re not already familiar with WP-CLI, WP-CLI is a command-line interface for WordPress. There are many commands available by default to make your day-to-day tasks easier. For example, you can activate the plugin by entering the command wp activate plugin wp-force-logout
without even opening your site or browser. How cool.
Currently, there is a list of commands you can use by default. However, you might want to create your own custom commands for your site.
The snippet for creating custom WP-CLI commands can be embedded within the theme’s functions.php just like any other code snippet. In case it helps, here’s how to easily add custom code snippets in WordPress. There are many ways of creating custom commands within the functions, class, closure, etc. The easiest way is to create a function for our custom command. So, let’s create a snippet to log out a user with a provided user ID.
function logout( $args, $assoc_args ) {
if ( condition ) {
WP_CLI::success( $args[0] );
}
}
WP_CLI::add_command( 'wpfl', 'logout' );
Once this snippet is added to your site, we’ve created a new command which is wp wpfl logout
Yay!
Usage:
wp wpfl logout 54
which means, $args[0]
will be 54 because $args
is an array. wp wpfl logout 43 23 12 14
which means $args
is array( '43', '23', '12', '14' );
For example 43, 23, 12, 14 are the user IDs, you’d like to log out.
So, the actual implementation would be:
function logout( $user_ids, $assoc_args ) {
foreach( $user_ids as $user_id ) {
// Perform your functionality. E.g. Logout users with these ids.
WP_CLI::line( 'User ' . $user_id . ' logged outt!' );
}
}
WP_CLI::add_command( 'wpfl', 'logout' );
Let’s know about the $assoc_args
. Anything passed with — in command will come up in $assoc_args
.
Usage:
wp wpfl logout 42 --force
Do different things if --force
is passed.
function logout( $user_ids, $assoc_args ) {
foreach( $user_ids as $user_id ) {
// Perform your functionality. E.g. Logout users with these ids.
WP_CLI::line( 'User ' . $user_id . ' logged outt!' );
if ( isset( $assoc_args['force'] ) ) {
// Do something.
}
}
}
WP_CLI::add_command( 'wpfl', 'logout' );
That’s all. I hope you found this helpful! Detailed implementation for the WP Force Logout plugin can be found in the plugin’s WPFOrce_Logout_CLI.php file.
What’s next? Check out some of my favorite WP-CLI Commands.