The post How to Create an Alias for Mac with Terminal (Bash or Zsh Shell) appeared first on PluginsForWP.
]]>One of the scenarios we use here on our WordPress website is when running promotions.
When running a sale on our website, we need to edit four files: style.css, functions.php, our Plugin Manager server file, and a specific JS file.
Up until the point I created the alias, I needed to navigate into each of the file folders and open them individually.
The command that I used to open them all was:
open store/wp-content/plugins/pluginsforwp-server/pluginsforwp-server.php store/wp-content/themes/oceanwp-child-theme-master/functions.php store/wp-content/themes/oceanwp-child-theme-master/scripts/general-scripts.js store/wp-content/themes/oceanwp-child-theme-master/style.css
A process like so will waste valuable time. Good developers should aim to be more productive and simplify operations. Therefore, creating an alias is precisely what I needed to do.
Thus, I created the alias promofiles to open all four files.
In the next section, I will show you how to set an alias in Unix environments, such as macOS, Bash, Zsh, and Linux.
The first type is a temporary alias, valid only for the current session (until closing the shell) or turning off your computer.
First, you’ll need to open the terminal. Then, use the syntax below:
alias <newcommand>='<old command>’
For example, if we would like to use the command pull to pull our WordPress website from git, we can create an alias like so:
alias pull=‘git pull origin master’
Once we set it up, we can execute the alias using the pull syntax.

If you would like to persist with the newly created alias and use it again in the future, we will need to save it permanently.
The advantage of a permanent alias is the option to reuse the syntax in the future, even after restarting our system.
To save the alias on our system, we will need to add it to the .bash_profile or .zshrc files.
The following steps will show you how to create an alias for macOS:
Launch the terminal from the Utility folder.
Type ~/ to navigate to your home directory.
Now, you’ll need to open the .bash_profile or the .zshrc file by entering open .zshrc (if you don’t have the file, create one first with the nano .zshrc command and open it afterward).
Scroll to the bottom of the .zshrc file and enter alias <newcommand>='<old command>’. For example: alias l='ls -lah’.
Save the file and exit it.
Run the alias in the terminal and verify it’s working.
That’s it. You just created an alias on your macOS that will make your developing job much quicker.
Any UNIX environment: Bash, Zsh, Fish on macOS and Linux.
Since the release of macOS 10.6, Zsh has been the default shell (replaced the bash shell).
Yes, there are many great tutorials that you can find on Google. This is the one we followed in the past and found beneficial.
Alias is a great way to prevent retyping repetitive commands and is very useful in saving valuable time.
Leave us a comment and let us know if you have any questions about the process or need any other command.
The post How to Create an Alias for Mac with Terminal (Bash or Zsh Shell) appeared first on PluginsForWP.
]]>The post Creating a custom wp-cli command appeared first on PluginsForWP.
]]>Last week, we learned how to use wp-cli to run commands for your WordPress install without using the GUI, and how to script commands to create batch operations. This week, we’ll learn how to create custom wp-cli commands that can run your own PHP code and do anything you want.
To start, we will create a simple WordPress plugin that will contain all of our code. You should first pick a name for your plugin. It’s advisable to use your company or organization name as a prefix. For example, my-company-cli-commands could be a good name for a company called My Company. Once you’ve decided on the name of your plugin (make sure there are no spaces or special characters not allowed in directory / file names), create a directory with that name in the WordPress plugins directory and switch to that directory:
mkdir my-company-cli-commands cd my-company-cli-commands
Inside this directory, you’ll want to create the main PHP file. It should have the same name as the directory with a .php extension. In our case, this will be my-company-cli-commands.php. You can use any editor for this. Once you’ve created the file, we need to add a PHP comment block at the top. Comments in PHP are generally ignored by PHP, but in the case of WordPress plugins and themes, this giant comment block at the top of the main PHP file is used by WordPress to obtain the metadata (name, version, compatibility, URLs, etc.) for the plugin. Here’s what it’ll look like for our new plugin:
<?php /** * My Company CLI Commands * * @package My Company * @author My Company * @copyright 2020 My Company * @license GPL * * @wordpress-plugin * Plugin Name: My Company CLI Commands * Plugin URI: https://my-company.com/ * Description: Adds wp-cli CLI commands to WordPress. * Version: 1.0.0 * Requires at least: 5.0 * Requires PHP: 7.4 * Author: My Company * Author URI: https://my-company.com/ * Text Domain: my-company-cli-commands * License: GPL */
If you’re writing an actual plugin, you would replace the names and URLs with your own. The version and license are up to you, though if you want to distribute your plugin later on wordpress.org, licensing it under the GPL license is necessary.
The Requires at least field is the minimum WordPress version you will support. Currently, the major WordPress version number is 5. Here, we are targeting version 5 and above. Depending on the features of your plugin, you may need to require a different WordPress version.
Likewise, the Requires PHP field is the minimum PHP version your plugin will support. Here, we have set it to 7.4. With the release of PHP 8 last year, it’s recommended that this be at least 7.3. All older versions are now obsolete and no longer supported for quite some time. Unfortunately, a lot of people are still running some version of PHP 5 in production. This is unfortunate and dangerous from a security standpoint. Not to mention slow (PHP 7 had a 2-3x speed increase over 5 and PHP 8 will be faster than 7). But sometimes, older versions need to be supported. If writing a plugin for the widest audience, supporting PHP 5 is still necessary. We are hopeful that WordPress will move to PHP 7+ in the future and also start supporting PHP 8 soon.
Now that we have the plugin, you can log into your admin site and activate it. Or activate it with wp-cli directly as we showed last week. It won’t do anything yet, but it is a real plugin.
Now let’s add some code:
WP_CLI::add_command( 'myco do something',
function () {
WP_CLI::line( 'Starting...' );
try {
// Call your custom code here
} catch ( \Throwable $e ) {
WP_CLI::error( $e->getMessage() );
throw $e;
}
WP_CLI::success( "Success!" );
}
);
This is the basic scaffolding for the command. You can add as many commands as you want this way. In this case, the command that you will run to invoke this code is:
wp myco do something
Remember to run that from inside the WordPress directory for it to work. Give it a try now. If it was successful, it should show:
Starting... Success!
The WP_CLI::line() function call just prints some information to your terminal, in this case, a message indicating that your command has started. The WP_CLI::success() call tells wp-cli that you have finished successfully (returns a 0 exit code to the shell for those that are familiar with Linux/BSD systems) and prints a message to the user indicating so.
If there is an error in your code, it will be caught by the catch block and the exception message will be printed to the console. The exception will be re-thrown. This will stop all execution and print a stack trace to help you see where and how the error was reached. This is extremely useful for debugging.
Now you have the scaffolding needed to add your custom commands. Once this executes successfully, you can add some code to replace the // Call your custom code here comment in the code above. I recommend you don’t just dump a bunch of code into this callback, but call another function or method. This way, the command is separated from the code that actually implements the command. It will be much easier to maintain and if you have a lot of commands, the implementation for each one can go in its own function, file, or class, depending on your preference. Here’s an example. First define a function to do something:
namespace MyCompany\CLI;
use WP_CLI;
class Commands {
/**
* Run the "do something" command
*/
public static function doSomething() {
// ...
}
}
In this case, I’ve created a namespace for our code, MyCompany\CLI, and created a class called Commands inside to hold our function. You can just create a function by itself, but if you will have complex functionality, it makes sense to encapsulate it in a class.
Finally, I’ve created a public, static function called doSomething. Because it’s public, it’s callable from anywhere, and because it’s static, we don’t have to instantiate the class first but can call it directly. I also added a use statement so we can call commands from the WP_CLI class from within our namespace. Now we modify the original code to make a call to this function:
WP_CLI::add_command( 'myco do something',
function () {
WP_CLI::line( 'Starting...' );
try {
Commands::doSomething();
} catch ( \Throwable $e ) {
WP_CLI::error( $e->getMessage() );
throw $e;
}
WP_CLI::success( "Success!" );
}
);
Now, upon running the command, your code in Command::doSomething() will be ran. What that code does is up to you. You have access to the full WordPress API that any plugin does and can do anything you need. Perhaps you need to load some data from an external source, update the date on some blog posts, or call out to some functionality from other plugins. Anything is possible.
In this post, we learned how to create a basic WordPress plugin. We also learned how to use wp-cli to create our own custom commands that can run any PHP code inside this plugin. Instead of just running the commands that wp-cli provides, we can now extend its functionality and provide brand new commands that are custom tailored to our sites and our needs. In the future, we will look into some ideas for commands you can write to simplify management of your WordPress sites and add functionality that neither WordPress or wp-cli provides. This should be a good start for you to be able to add your own CLI commands or use CLI commands to trigger internal WordPress APIs or other plugins.
The post Creating a custom wp-cli command appeared first on PluginsForWP.
]]>The post Using WP-CLI to Manage WordPress on the Command Line appeared first on PluginsForWP.
]]>git to manage revisions of your code, you might still be wondering: why would you want to do anything from the command line, let alone manage your WordPress site this way? There are many reasons. It is often faster and easier than using a graphical interface (GUI). The commands are repeatable and scriptable. This means that you can write scripts of commonly used commands or chains of commands and execute them easily later. It can remove a lot of boring busy work from your life.
These commands or scripts can also be shared with others who can benefit and who can introduce their own ideas and improvements. It is also more accurate and exact. When a command runs successfully, you get immediate feedback. You can easily run commands for many WordPress installations without having to log into the graphical admin interface. You can also run many other commands not directly related to WordPress, and combine them in an almost unlimited number of useful ways to achieve what you want.
It is often easier to do even the most basic of computer tasks on the command line. For example, if you want to copy a file from one location to another, you’d run:
cp /path/to/my/file /path/to/my/destination/directory_or_file
That’s it. One command. you don’t have to open up the Finder or Explorer, find the file, open up another window or tab, and drag it over. Just one command in your terminal and you’re done. If there’s an error, it’ll be immediately obvious. Afterwards, you can move on to other tasks.
wp-cliwp-cli is a command line tool to manage WordPress installations from the command line. To use any command line tools, you first need a terminal program. Terminal.app or iTerm2 on a Mac, any Linux terminal app like Konsole for Linux, or Windows Terminal for Windows are all good starting points.

Open up your terminal. Let’s first install wp-cli. Check out the installation instructions at the wp-cli website. You will download a Phar file which is basically a self-contained PHP program that has everything it needs to run, change the permissions to make it executable, and copy it to a system location. If you’re on a Mac with Homebrew, you can also just run:
brew install wp-cli
and Homebrew will take care of the installation for you. I would recommend that for any Mac users.
Now that you’ve installed wp-cli, open up a new terminal window and try running it to make sure it works:
wp
You should see output similar to the below:
NAME wp DESCRIPTION Manage WordPress through the command-line. SYNOPSIS wp <command> SUBCOMMANDS cache Adds, removes, fetches, and flushes the WP Object Cache object. cap Adds, removes, and lists capabilities of a user role. cli Reviews current WP-CLI info, checks for updates, or views defined aliases. comment Creates, updates, deletes, and moderates comments. config Generates and reads the wp-config.php file. core Downloads, installs, updates, and manages a WordPress installation. cron Tests, runs, and deletes WP-Cron events; manages WP-Cron schedules. db Performs basic database operations using credentials stored in wp-config.php. embed Inspects oEmbed providers, clears embed cache, and more. eval Executes arbitrary PHP code. eval-file Loads and executes a PHP file. export Exports WordPress content to a WXR file. help Gets help on WP-CLI, or on a specific command. i18n Provides internationalization tools for WordPress projects. import Imports content from a given WXR file. language Installs, activates, and manages language packs. maintenance-mode Activates, deactivates or checks the status of the maintenance mode of a site. media Imports files as attachments, regenerates thumbnails, or lists registered image sizes. menu Lists, creates, assigns, and deletes the active theme's navigation menus. network Perform network-wide operations. option Retrieves and sets site options, including plugin and WordPress settings. package Lists, installs, and removes WP-CLI packages. plugin Manages plugins, including installs, activations, and updates. post Manages posts, content, and meta. post-type Retrieves details on the site's registered post types. rewrite Lists or flushes the site's rewrite rules, updates the permalink structure. role Manages user roles, including creating new roles and resetting to defaults. scaffold Generates code for post types, taxonomies, plugins, child themes, etc. search-replace Searches/replaces strings in the database. server Launches PHP's built-in web server for a specific WordPress installation. shell Opens an interactive PHP console for running and testing PHP code. sidebar Lists registered sidebars. site Creates, deletes, empties, moderates, and lists one or more sites on a multisite installation. super-admin Lists, adds, or removes super admin users on a multisite installation. taxonomy Retrieves information about registered taxonomies. term Manages taxonomy terms and term meta, with create, delete, and list commands. theme Manages themes, including installs, activations, and updates. transient Adds, gets, and deletes entries in the WordPress Transient Cache. user Manages users, along with their roles, capabilities, and meta. widget Manages widgets, including adding and moving them within sidebars.
As you can see, wp-cli has a lot of different commands you can run to manage your WordPress install. In this article, we’ll cover some of the more useful ones.
Let’s start off with the plugin command. This allows you to manage your plugins by installing, uninstalling, activating, deactivating, and updating your plugins. First, run the command by itself to see the various options:
wp plugin
It will output the following:
usage: wp plugin activate [<plugin>...] [--all] [--network] or: wp plugin deactivate [<plugin>...] [--uninstall] [--all] [--network] or: wp plugin delete [<plugin>...] [--all] or: wp plugin get <plugin> [--field=<field>] [--fields=<fields>] [--format=<format>] or: wp plugin install <plugin|zip|url>... [--version=<version>] [--force] [--activate] [--activate-network] or: wp plugin is-active <plugin> or: wp plugin is-installed <plugin> or: wp plugin list [--<field>=<value>] [--field=<field>] [--fields=<fields>] [--format=<format>] or: wp plugin path [<plugin>] [--dir] or: wp plugin search <search> [--page=<page>] [--per-page=<per-page>] [--field=<field>] [--fields=<fields>] [--format=<format>] or: wp plugin status [<plugin>] or: wp plugin toggle <plugin>... [--network] or: wp plugin uninstall [<plugin>...] [--deactivate] [--skip-delete] [--all] or: wp plugin update [<plugin>...] [--all] [--exclude=<name>] [--minor] [--patch] [--format=<format>] [--version=<version>] [--dry-run] or: wp plugin verify-checksums [<plugin>...] [--all] [--strict] [--format=<format>] See 'wp help plugin <command>' for more information on a specific command.
Let’s install a new plugin. You’ll need to be in the directory of your WordPress installation to run the following commands as they affect the WordPress installation in the directory they are ran in. You can install a plugin from a zip file or URL. We’ll install the Classic Editor plugin to demonstrate. For convenience, we’ll use a URL.

First, we’ll get the URL by copying it from the Download button on the plugin page at wordpress.org.

Then run:
wp plugin install https://downloads.wordpress.org/plugin/classic-editor.1.6.zip
You’ll see something like this if it was successful:
Downloading installation package from https://downloads.wordpress.org/plugin/classic-editor.1.6.zip... The authenticity of classic-editor.1.6.zip could not be verified as no signature was found. Unpacking the package... Installing the plugin... Plugin installed successfully. Success: Installed 1 of 1 plugins.
Now let’s activate that plugin:
wp plugin activate classic-editor
Which should output:
Plugin 'classic-editor' activated. Success: Activated 1 of 1 plugins.
Nice. We’ve installed this plugin and activated it. All with two commands. Since this is such a common operation, you could actually install and activate the plugin with one command:
wp plugin install --activate https://downloads.wordpress.org/plugin/classic-editor.1.6.zip
You could easily copy that command and put it into a script along with commands to install all the plugins you need. For example, the following script installs and activates 3 plugins:
#! /bin/bash wp plugin install --activate https://downloads.wordpress.org/plugin/classic-editor.1.6.zip wp plugin install --activate https://downloads.wordpress.org/plugin/contact-widgets.1.7.0.zip wp plugin install --activate https://downloads.wordpress.org/plugin/wd-youtube.1.0.33.zip
Save that in a file in the root of your WordPress installation called install.sh. You can call the script whatever you want but it’s advised to keep the sh extension which indicates it’s a shell script, in our case a bash shell script. Now run the following to make it executable:
chmod +x install.sh
That will allow you to execute it by either typing its full path name or, from the current directory, running it as:
./install.sh
Note that ./ indicates the current directory (the . in that expression) along with the directory separator / (which would be \ on Windows).
If everything went according to plan, you’ll see the following:
Downloading installation package from https://downloads.wordpress.org/plugin/classic-editor.1.6.zip... The authenticity of classic-editor.1.6.zip could not be verified as no signature was found. Unpacking the package... Installing the plugin... Plugin installed successfully. Activating 'classic-editor'... Warning: Plugin 'classic-editor' is already active. Success: Installed 1 of 1 plugins. Xdebug: [Step Debug] Could not connect to debugging client. Tried: localhost:9000 (fallback through xdebug.client_host/xdebug.client_port) :-( Downloading installation package from https://downloads.wordpress.org/plugin/contact-widgets.1.7.0.zip... The authenticity of contact-widgets.1.7.0.zip could not be verified as no signature was found. Unpacking the package... Installing the plugin... Plugin installed successfully. Activating 'contact-widgets'... Warning: Plugin 'contact-widgets' is already active. Success: Installed 1 of 1 plugins. Xdebug: [Step Debug] Could not connect to debugging client. Tried: localhost:9000 (fallback through xdebug.client_host/xdebug.client_port) :-( Downloading installation package from https://downloads.wordpress.org/plugin/wd-youtube.1.0.33.zip... The authenticity of wd-youtube.1.0.33.zip could not be verified as no signature was found. Unpacking the package... Installing the plugin... Plugin installed successfully. Activating 'wd-youtube'... Plugin 'wd-youtube' activated. Success: Installed 1 of 1 plugins.
As you can see, this is a very powerful, simple, and easy way to install plugins. You can create a script with the plugins you typically use and run it in all of your WordPress installs.
You can also remove plugins:
wp plugin delete classic-editor
Resulting in:
Deleted 'classic-editor' plugin. Success: Deleted 1 of 1 plugins.
Or update:
wp plugin update classic-editor
Which yields:
Success: Plugin already updated.
In this case, there was no update available, but if there was one, it would have updated the plugin.
We will cover one more wp-cli command today and more in later blog posts. The wp server command will start a development server with your WordPress site running and ready to be worked on. All you need to do is run:
wp server
If it is successful in starting the server, you’ll see something like the below:
[Fri Jan 29 16:55:54 2021] PHP 7.4.14 Development Server (http://localhost:8080) started
If you get an error about the port (8080 by default) being used, you can try a different port until you find one that’s free like this:
wp server --port=6000

You can navigate to the URL (by default http://localhost:8080) and you’ll see your WordPress site! This is a quick way to test your site and work on it without having to install a web server and configure it yourself. The MySQL database server still needs to be installed and running so if you plan on using this technique to develop and test locally, you should look into instructions on installing the community port of MySQL, MariaDb.
In this article, we learned why you would want to use the command line and how to install wp-cli to manage WordPress sites. We learned how to use wp-cli to install, activate, delete, and update plugins, and how to script these operations and batch them up so multiple operations can be ran with one command. Finally, we learned how to start a development server to work on and test our WordPress sites. In future blog posts, we’ll explore other wp-cli commands and features, including the ability to create your own custom commands that allow you to do virtually anything with a WordPress installation by running custom PHP code.
The post Using WP-CLI to Manage WordPress on the Command Line appeared first on PluginsForWP.
]]>