Display Data in Table, JSON, or CSV Format

Advertisement

From the last few articles, we are familiar with the WP CLI command.

In this article let’s learn about how to display custom data in the table, JSON or CSV format.

Note: If you read some recent articles then you can skip some below steps that are related to plugin creation.

Create Empty Plugin Create Empty Plugin

  • Create a new folder wordpress-examples into plugins directory /wp-content/plugins/
  • Create a file wordpress-examples.php and add the below code into it.
<?php
 /**
 Plugin Name: WordPress Examples
 */ 

Note: If you want to add some additional information then you can get it from gist snippet – WordPress Complete Plugin Readme File.

Now you can see our WordPress Examples plugin exists into the plugins list.

Display Data in Table, JSON, or CSV Format with WP CLI Formatter 1
Display Data in Table, JSON, or CSV Format with WP CLI Formatter 3

Now, Activate the WordPress Examples plugin.

Display Data in Table, JSON, or CSV Format with WP CLI Formatter 2
Display Data in Table, JSON, or CSV Format with WP CLI Formatter 4

Top ↑

Register WP CLI Command Register WP CLI Command

Register PHP class WordPress_Examples_WP_CLI e.g.

if ( ! class_exists( 'WordPress_Examples_WP_CLI' ) && class_exists( 'WP_CLI_Command' ) ) :
       class WordPress_Examples_WP_CLI extends WP_CLI_Command {

       }
endif;

Here,

We have registered a new class WordPress_Examples_WP_CLI and extend it with WP_CLI_Command.

Top ↑

Add Examples Command Add Examples Command

Now let’s register the examples. E.g.

       WP_CLI::add_command( 'examples', 'WordPress_Examples_WP_CLI' ); 

Here,

We have used the function WP_CLI::add_command() to register our examples command.

The function WP_CLI::add_command() accepts 2 parameters. The first parameter is the command name. Which is examples in our case.

And second is a callback class which is WordPress_Examples_WP_CLI.

Top ↑

Add list sub command Add list sub command

         public function list( $args, $assoc_args ) {
           WP_CLI::line( 'Hello' );
         }

Here,

We have added a function list() with two parameters.

  • $args contain the arguments.
  • $assoc_args contain the associate arguments.

Top ↑

Testing the Command Testing the Command

Open command prompt/terminal. Go to your WordPress setup. I have set up WordPress in D:\xampp\htdocs\dev.test

So, Execute the below commands:

  • cd D:\xampp\htdocs\dev.test
  • wp examples list

You can see the output something like below:

 ? wp examples list
 Hello

This command just shows the string Hello.

For testing, let’s create a static array which have some dummy data.

public function list( $args, $assoc_args ) {
	$list = array(
		array(
			'id'    => '1',
			'first' => 'Mahesh',
			'last'  => 'Waghmare',
		),
		array(
			'id'    => '2',
			'first' => 'Swapnil',
			'last'  => 'Dhanrale',
		),
		array(
			'id'    => '3',
			'first' => 'Madhav',
			'last'  => 'Shikhare',
		),
	);
	WP_CLI::line( print_r( $list ) );
}

Let’s execute the command wp examples list.

 ? wp examples list
 Array
 (
      [0] => Array
         (
             [id] => 1
             [first] => Mahesh
             [last] => Waghmare
         )
      [1] => Array
         (
             [id] => 2
             [first] => Swapnil
             [last] => Dhanrale
         ) 
      [2] => Array
         (
             [id] => 3
             [first] => Madhav
             [last] => Shikhare
         ) 
 )
 1

Here, we have just print the array with WP_CLI::line( print_r( $list ) );.

Now, Let’s display this array data in a well-formatted order.

Top ↑

Using \WP_CLI\Formatter() Using \WP_CLI\Formatter()

We are using the in-build WP CLI helper class \WP_CLI\Formatter() to format our array in table format.

Let’s use the Formatter class into our code:

public function list( $args, $assoc_args ) {
	$list = array(
		array(
			'id'    => '1',
			'first' => 'Mahesh',
			'last'  => 'Waghmare',
		),
		array(
			'id'    => '2',
			'first' => 'Swapnil',
			'last'  => 'Dhanrale',
		),
		array(
			'id'    => '3',
			'first' => 'Madhav',
			'last'  => 'Shikhare',
		),
	);
	$formatter = new \WP_CLI\Formatter( $assoc_args, array(
		'id',
		'first',
		'last',
	));
	$formatter->display_items( $list );
}

Here,

  • $formatter We have created a variable which stores the instance of the class new \WP_CLI\Formatter().
  • new \WP_CLI\Formatter class initialized bypassing 2 values.
    • $assoc_args – which contain the associated arguments.
    • array( 'id', 'first', 'last') – It contains the keys of our array.
      We will check some examples below to understand why it was passed.
  • $formatter->display_items( $list ); – We have called the display_items() method of Formatter class and pass the $list into it.

Let’s try some commands to see how it works.

wp examples list

After executing above command we see the output like:

? wp examples list
 +----+---------+----------+
 | id | first   | last     |
 +----+---------+----------+
 | 1  | Mahesh  | Waghmare |
 | 2  | Swapnil | Dhanrale |
 | 3  | Madhav  | Shikhare |
 +----+---------+----------+

Hurray! Our array is displayed in the table format. Because of by default class \WP_CLI\Formatter() display items in Table format.

If we want to see the same data in another format then we need to set associate argument --format

Top ↑

Using –format Using –format

Let’s try another example with --format associate argument.

Example 1

wp examples list --format=json

After executing above command we can see the result something like below:

? wp examples list --format=json
 [{"id":"1","first":"Mahesh","last":"Waghmare"},{"id":"2","first":"Swapnil","last":"Dhanrale"},{"id":"3","first":"Madhav","last":"Shikhare"}]

Here, We have passed the --format=json for that, the data is display as JSON.

Example 2

wp examples list --format=csv

After executing above command we can see the result something like below:

? wp examples list --format=csv
 id,first,last
 1,Mahesh,Waghmare
 2,Swapnil,Dhanrale
 3,Madhav,Shikhare

In the --format associate argument we can pass values ‘table‘, ‘json‘, ‘csv‘, ‘yaml‘, ‘ids‘ and ‘count‘.

Try some other format yourself and understand how it displays it.

Top ↑

Using –field Using –field

In our example, we have 3 keys those are id, first and last.

Let’s assume that we have 15+ keys. So, when we execute our list command then all the data will be display.

Maybe we just want to display a single column.

With the --field the associate argument we can display only specific column data.

Example 1

wp examples list --field=id

After executing above command we can see the result something like below:

? wp examples list --field=id
 1
 2
 3
 D:\xampp\htdocs\dev.test

Here, Only Id’s column is visible for us.

Example 2

wp examples list --field=id --format=json

We have used --field=id and --format=json. Let’s see what it display.

? wp examples list --field=id --format=json
 ["1","2","3"]

Example 3

wp examples list --field=ID

The output of the above command is below:

D:\xampp\htdocs\dev.test
 ? wp examples list --field=ID
 Error: Invalid field: ID.

Aah! Why it display the error? Because the value of the field is case sensitive. So all the below values considered as different:

  • --field=ID
  • --field=Id
  • --field=iD
  • --field=id

Top ↑

Using –fields Using –fields

Same as --field the argument we can use --fields.

The only difference is that we can pass multiple arguments into it.

Let’s try some examples.

Example 1

wp examples list --fields=id,first
? wp examples list --fields=id,first
 +----+---------+
 | id | first   |
 +----+---------+
 | 1  | Mahesh  |
 | 2  | Swapnil |
 | 3  | Madhav  |
 +----+---------+

Here, We can see only the id and the first column.

Example 2

wp examples list --fields=first,id

Let’s try to change the sequence of the keys by passing values first and then id.

? wp examples list --fields=first,id
 +---------+----+
 | first   | id |
 +---------+----+
 | Mahesh  | 1  |
 | Swapnil | 2  |
 | Madhav  | 3  |
 +---------+----+

Interesting right! Let’s get the first and last column in JSON format.

Example 3

wp examples list --fields=first,last --format=json

Here, we have passed the --fields=first,last and --format=json.

The output is as below:

? wp examples list --fields=first,last --format=json
 [{"first":"Mahesh","last":"Waghmare"},{"first":"Swapnil","last":"Dhanrale"},{"first":"Madhav","last":"Shikhare"}]

Showing data in the table, JSON or CSV format in WP CLI program!

Leave a Reply