0
Php

WP-CLI – The Command Line Tool For WordPress

Probably the WordPress is one of the most used CMS and blogging platform on the web and also it’s probably the most criticized one in the PHP community as well, because the way it works but not sure about that so pardon me if I’m wrong. Anyways, so whatever it’s but it has dominated the web for a long period of time and like this one, no other CMS or application (or whatever you call it) could made so far. It’s still very active and serving pretty well. Although it was built as blogging platform but by the time and effort of the developer community it become one of the major CMS and it’s been used for not not only as a blogging tool or CMS but also it’s been used to build complex e-commerce sites and other complex web applications. One of the biggest advantages is that, it’s plug-n-play, I mean, for every single need there is a plugin available and even non-programmers (advanced uses) can easily install it and can run the system for their online shipping sites with a very less effort because plenty of themes and plugins are just only one click a way. If you know how to search and where to search for a theme or plugin then you can start an online shopping site without writing any code.

But, time has been changed and our expectations are being higher. Now, it’s time for modern programming techniques and tools like composer, bower, behat, codeception and so many cool things that become one of the part of our daily development process and we can’t think anything without OOP. In this case, WordPress doesn’t meet the needs. Well, probably it does but we just think it like this, such as it’s all about messy templating with a mash up of HTML and PHP code, which sounds a boring task but probably there are better ways to use WordPress using modern programming tools and techniques. Well, actually we can write clean code with WordPress using modern testing tools like behat and dependency manager like composer and we may integrate templating engines like twig and blade as well to write clean code for building a WordPress theme.

There is already a plugin (could be more) called timber which helps to build a template using twig templating engine which cleans-up your theme code so your PHP file can focus on supplying the data and logic, while your twig file can focus completely on the presentation. You may read more about timber.

Also there is a nice framework (I was not aware of this before) called Themosis which uses MVC pattern and expressive syntax like famous framework Laravel and also uses the blade templating engine of Laravel. It has a very elegant routing system and it uses composer to build a modern WordPress stack by default. So check it if didn’t yet. probably there are other beautiful stuffs out there but anyways. These are extra dependencies for WordPress but even without using these tools we are able to write clean OOP code in WordPress to build plugins and themes.

Anyways, one of the most amazing things that really a cool addition into the WordPress is it’s Command Line Tool which is not very new but not even very old and it’s WP-Cli.

WP-CLI is a set of command-line tools for managing WordPress installations. You can update plugins, set up multisite installs and much more, without using a web browser.

This tool is really one of the sexiest things in WordPress and it’s very helpful for developers, it lets download and install WordPress from command line and also we can use it to manage the site very easily and not only this but also we may generate code snippets to speed up our development process. It’s very easy to install, just visit the home page and read the instructions. Notice there are alternative install methods available and it can be done using composer as well. Okay, enough talk, now let see some examples, I’ve installed it using composer by running following command from my terminal:

> composer create-project wp-cli/wp-cli --no-dev

It’s possible to install it globally, to do that, just create a folder and use cd folder to get into that folder then run the above command so it’ll be installed in that directory and make sure to add the executable path in your path (for windows) or move it to the bin directory for nix base OS. Once it’s installed then check if it works by running wp from your command line. It’ll show some information including it’s current version number. Now lets download WordPress from command line using WP-Cli, run following commands step by step:

# Download WordPress in the current directory
> wp core download

Then create a database (I’m using mysql from command prompt):

# Log into mysql (Make sure your mysql executable is accessible from your current folder)
> mysql -u root -pyourpassword;

# create a new database
> create database wpcli_test;

#Exit out from mysql
> exit;

Then run the following command to provide log in credentials:

# Provide your login credentials
> wp core config --dbname=wpcli_test --dbuser=root --dbpass=yourpassword

Then run the following command to start installation:

# Provide following options properly
# url, title, admin_user, admin_password, admin_email
> wp core install --url=http://localhost/your-project-directory --title=SiteTitle --admin_user=wplogin --admin_password=wppassword --admin_email=your@mail.com

If everything want right then WordPress will be installed within a few seconds. That’s it, without using the mouse, just from command line the WordPress has been installed very easily. Well, that’s not all but now we’ll see some more examples that we can run from command prompt using WP-Cli but there are many commands and I won’t cover all so visit the WP-Cli website to check fill list of commands.

WP-CLI has a series of global parameters which work with all commands. They can be specified either as flags for the wp executable in the terminal, or defined in a YAML config file.

It’s possible to create a post from command line using following command:

# Create a Post
> wp post create --post_type=post --post_title="A post" --post_status=publish

To create a post using content from a file, use create command:

# Create a Post but use content from post-content.txt file in current directory
> wp post create ./post-content.txt --post_category=1 --post_title="A Post from file"

To update a post use update command:

# Update the Post whose id is 5; set post_status=publish
> wp post update 5 --post_status=publish

Check wp post command for more sub-commands such as wp post list to view a list of your posts or wp post delete for deleting a post and many more.

To generate some post samples for testing you may use generate command:

# Generate 5 Pages (in database) with specific date
> wp post generate --count=5 --post_type=page --post_date=1999-01-04

To generate some post samples for testing but give input from remote server:

# Generate 10 Posts (in database) give post_content from web using curl
> curl http://loripsum.net/api/5 | wp post generate --post_content --count=10

To generate some code snippet (scaffold) for a custom taxonomy use scaffold command:

# Auto generate a code snippet for custom taxonomy
> wp scaffold taxonomy venue --post_types=event,presentation

This will dump the code to std_out (console) and you need to copy and paste it in your script file but you may also generate the code and dump it into a file using following command:

# Auto generate a code snippet for custom taxonomy but save the code in a file, in twentytwelve theme folder
> wp scaffold taxonomy venue --post_types=event,presentation --theme="twentytwelve"

Above command will generate the code snippet and then it’ll create a folder “texonomies” in tweentytwelve folder and then it’ll save the code in venue.php file. The code will look something like this:

 false,
		'public'            => true,
		'show_in_nav_menus' => true,
		'show_ui'           => true,
		'show_admin_column' => false,
		'query_var'         => true,
		'rewrite'           => true,
		'capabilities'      => array(
			'manage_terms'  => 'edit_posts',
			'edit_terms'    => 'edit_posts',
			'delete_terms'  => 'edit_posts',
			'assign_terms'  => 'edit_posts'
		),
		'labels'            => array(
			'name'                       => __( 'Venues', 'twentytwelve' ),
			'singular_name'              => _x( 'Venue', 'taxonomy general name', 'twentytwelve' ),
			'search_items'               => __( 'Search venues', 'twentytwelve' ),
			'popular_items'              => __( 'Popular venues', 'twentytwelve' ),
			'all_items'                  => __( 'All venues', 'twentytwelve' ),
			'parent_item'                => __( 'Parent venue', 'twentytwelve' ),
			'parent_item_colon'          => __( 'Parent venue:', 'twentytwelve' ),
			'edit_item'                  => __( 'Edit venue', 'twentytwelve' ),
			'update_item'                => __( 'Update venue', 'twentytwelve' ),
			'add_new_item'               => __( 'New venue', 'twentytwelve' ),
			'new_item_name'              => __( 'New venue', 'twentytwelve' ),
			'separate_items_with_commas' => __( 'Venues separated by comma', 'twentytwelve' ),
			'add_or_remove_items'        => __( 'Add or remove venues', 'twentytwelve' ),
			'choose_from_most_used'      => __( 'Choose from the most used venues', 'twentytwelve' ),
			'menu_name'                  => __( 'Venues', 'twentytwelve' ),
		),
	) );

}
add_action( 'init', 'venue_init' );

All you need to do is that, just include the file in your functions.php file and the code will run and a custom taxonomy will be created (edit the code if needed then save). Check the wp scaffold command for more sub-commands, you may generate code snippet for Child Theme, Plugin and Post Types and many others. There are some other commands are available as well and those are also very useful, so check the website for full list of commands. Also, there are a bunch of community commands are available as external commands, which means anyone can create custom commands and for to learn more about creating a custom command check Commands Cookbook and also check this Contributor guide if you want to contribute.

So far, it’s good enough and currently another version is under development and in that version the Boris will be added for interactive PHP console as wp shell command.

Well, it’s all for this article. To be honest, this is really a great addition to WordPress and hope the WordPress community will keep it (WordPress) alive and take it to the next level which will bring back the joy of coding.

Latest Blog

0
Php

PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]