Using WordPress ‘get_cli_args()’ PHP function

The get_cli_args() WordPress PHP function returns the value of command line parameters and exits when a required parameter is not set.

Usage

$value = get_cli_args($param, $required = false);

Parameters

  • $param (string): The parameter name.
  • $required (bool): Optional. Determines if the parameter is required. Default is false.

More information

See WordPress Developer Resources: get_cli_args

Examples

Get optional command line parameter

Retrieve the value of an optional command line parameter “filename”.

$filename = get_cli_args('filename');
// If 'filename' parameter is provided, the value will be stored in $filename variable

Get required command line parameter

Retrieve the value of a required command line parameter “task”. The script will exit if the parameter is not set.

$task = get_cli_args('task', true);
// If 'task' parameter is not provided, the script will exit

Set default value for optional command line parameter

Retrieve the value of an optional command line parameter “count” and set a default value if not provided.

$count = get_cli_args('count') ?: 10;
// If 'count' parameter is not provided, the default value (10) will be used

Multiple command line parameters

Retrieve the values of multiple command line parameters “task” and “filename”. “task” parameter is required, while “filename” is optional.

$task = get_cli_args('task', true);
$filename = get_cli_args('filename');
// If 'task' parameter is not provided, the script will exit

Check if command line parameter is set

Check if the command line parameter “verbose” is set.

$is_verbose = get_cli_args('verbose') !== null;
// If 'verbose' parameter is provided, $is_verbose will be true, otherwise false