WP Bootstrap 0.4.0, now a wp-cli sub command

Dr Martens - spring edition

 

So, as this post is written, the test suite for WP Bootstrap 0.4.0 all turned green and a new version is about to get tagged and available via composer. This release is a big one. If you’re the least bit interested in managing WordPress in a proper deployment workflow, I think you should continue reading.

Selection_466

Tighter wp-cli integration

This is the first release of WP Bootstrap that is entirely intended to be used as a wp-cli sub command. That means that instead of using WP Bootstrap as a stand alone command (or via composer scripts), all WP Bootstrap actions are now sub commands of wp-cli. Where we’d previously would have typed:

$ composer wp-setup

We’ll now be typing

$ wp bootstrap setup

That might seem as a very small change and on the surface I admit it is. But underneath the hood it has meant a lot of changes like replacing almost all external calls to wp-cli via exec() to using the internal wp-cli methods. Since wp-cli comes with functions for logging, output formatting and most importantly, internal functions for running other wp-cli commands, a lot of code has been cleaned up and Monolog  as well as Phpleague CLImate was replaced with corresponding wp-cli functionality. Last but not least, WP Bootstrap now uses Pimple for dependency management because it’s one of the few with the same PHP version requirements as wp-cli itself.

Settings files with dotenv and Yaml

Previous versions of WP Bootstrap has used json files for both application and local settings. Since json is not really that suitable for configuration files they are now gone.

Environment specific settings was previously kept in localsettings.json but are now replaced with dotenv files. Most DevOps engineers are familiar with dotenv files and several provisioning and deployment systems has support for working with them. So one of the benefits of switching formats is that more engineers will recognize them. WP Bootstraps uses Vance Lucas implementation of dotenv which enables a very elegant way of overloading values from several dotenv files. By defining that we’re working in environment ‘test’, we can have WP Bootstrap first load values from the base .env file and if it exists, overlay with values picked up from .env-test.

A bigger change is that appsettings.json is now replace with appsettings.yml. The format is pretty much still the same and converting an old appsettings.json can be done in seconds using a service like JSON to YAML Online. The main benefit of switching to Yaml is that Yaml allows comments. For a configuration file that keeps on growing this is surprisingly important. Just like dotenv, Yaml files are already quite popular among a lot of DevOps engineers, probably because Ansible uses them. And the fact that wp-cli itself relies on Yaml made the decision quite easy.

Feature upgrades

There are a few new features, some of them technically saw the light of day earlier than 0.4.0 but haven’t been previously announced (besides in the change log):

Extensions

Yes, WP Bootstrap now supports having extensions that can react to actions and filters. An extension is just a PHP class that implements the method ‘init’. In the init-method the extension can hook up to a few filters and actions. The PHP class can be loaded using Composer auto loading or it can exist as part of a theme or plugin. WP Bootstrap just needs to know the name of the class and you just need to make sure it implements the init-method.

The use case for this is to provide a way to perform extra processing during export and import. For instance, we’ve written a WooCommerce extension that handles import and export of the custom database tables that WooCommerces adds to a WordPress install. I expect to find the time to write blog posts on this topic really soon because it opens up a whole lot of new use cases for WP Bootstrap.

Plugin dependencies

Another important new feature is the ability to define dependencies between plugins and themes. Some plugins (mostly) simply will not install correctly or at all unless some other plugin or theme is already in place. To mitigate this, WP Bootstrap now allows you to define which other themes or plugins that needs to exist before this one gets installed.

Performance

When importing lots of media files, WP Bootstrap would always regenerate all thumbnails. When dealing with hundreds or even thousands of images, this becomes very time consuming. WP Bootstrap now checks if an updated image was actually changed before generating the thumbnails again. In a similar way, in the setup phase, WP Bootstrap would try to reinstall plugins even if they were already installed. While wp-cli would refuse to do the actual work, the plugin file would be downloaded from the repo on every attempt which costs a lot of time.

Removed features

Since WP Bootstrap is now just a wp-cli command, there’s no real need for keeping the upgrade commands for themes and plugins anymore. For command line management of plugin versions, you are better of using the standard wp-cli commands instead.

Test coverage

Refactoring tests and using with WP_Mock

Code quality is still one of the most important aspects of WP Bootstrap development, so a lot of time was spent on refactoring code and making sure code coverage remains high. Tests are now divided into unit tests and functional tests. Unit tests uses WP_Mock and manages to get up to about 50% code coverage without even needing a proper WordPress installation or a database. It should be possible to reach near 100% coverage for the unit tests, but we’re not quite there yet.

The other half of testing is made using functional tests. The functional tests requires a WordPress installation to work. Generally, the functional tests are easier to write but they are also much slower to run. Some tests are also impossible to get code coverage measurements from. As of the 0.4.0 release, functional tests covers roughly 66% of the code base but the overlap with the unit tests are quite high. Together unit tests and functional tests covers about 82%. That’s actually down a little bit compared to version 0.3.0 and that’s obviously an area to focus on going forward.

 

All test cases are still kept in a separate github repo just for testing. If you want to contribute to WP Bootstrap, this is where I recommend you start looking. Any contributions to WP Bootstrap are more than welcome, you can just send a pull request or better, shoot me an email first at: erik@wpessentials.io

 

WP Bootstrap 0.3.1 released

Lots of spare time over the holidays means a lot of work can go into WP Bootstrap. Version 0.3.1 brings a few bug fixes and small but nice new feature

Version 0.3.0 had support for working with taxonomy terms that are named after a post id. That was a nice feature, but it turns out that the import process had to run twice for the import to work properly due to a PHP type conversion problem. The export of special taxonomies was enhanced with a WARNING message in the logs if the configuration isn’t correct.

The new feature is wp-cli related. Runnit the wp-init command generates localsettings and appsettings unless they already exist. In 0.3.1, it also creates a wp-cli.yml file that defines the path to the WordPress installation. The condition is that localsettings.json exists and that the wppath parameter in it is different from the default “[wppath]” value. So run wp-init once to get a template localsettings file and edit it. Run wp-init again to get a wp-cli.ym file.

The benefit of defining the path to WordPress in a .yml file is to reduce typing when running commands.

 

Tutorial: Preparing a WordPress site for Git using WP Bootstrap

There are a lot of tutorials around about how to use Git to manage WordPress installations. While they are almost all very good, many of these tutorials encourage a work flow that works great for code but less than great, or not at all, for WordPress content. While most content in a WordPress site is just posts, comments and images some of the content is actually more important. Besides code, your WordPress site is also made up of menus, pages, widgets and options to work and look as you designed it, and in WordPress, most of that is also content. So we need an improved way of managing “application content” as opposed to “content content” to be able to maintain a good development work flow with Git.

In this tutorial, we’re going to go through all steps needed to setup a simple WordPress one-page site using WP Bootstrap as the main tool for migrating content. Since the site is created using WP Bootstrap, it’s also extremely easy to manage under Git source code control and to migrate it to a production environment. This text assumes that you have a basic understanding about Vagrant and some experience from a Linux command line will not hurt either. This text also assumes that you’re working on a Mac on Linux computer rather than Windows. Most commands will work the same on Windows, but please note that the author hasn’t tested.

Overview

We’re going to cover a few different areas.

  • First we’re going to create a Vagrant machine that we use as the development environment.
  • In the Vagrant machine, we’ll work with wp-cli, composer and WP Bootstrap which are our main tools to build up the site.
  • We will walk through how to modify appsettings.json, the main WP Bootstrap configuration file, to include just the parts of the content we want to manage using WP Bootstrap and show how export that content.
  • At last, we’ll re-import this content to an empty WordPress installation to verify that the process works as intended.

As the end result, we’re going to have a Git manageable WordPress site that takes content into account.

Step 1: Creating the Vagrant machine

Note: This guide does not aim to specifically teach anything about setting up and using Vagrant. If you want to read up on the basics of developing WordPress sites on top of Vagrant, please read this post. By the way, the rest of this text assumes that you have the vagrant plugin vagrant-hostupdater installed, as described in the linked post.

The first thing we’re going to do is to download a suitable Vagrant skeleton configuration. We’re going to use a derivative of Varying Vagrant Vagrants (vvv) with a little simplified setup that I’ve made available on Github. Open a terminal window and navigate to the folder where you keep your source code, the actual project folder will be created as part of this step, so don’t create that manually.

Get the zip, unzip it and rename the

$ wget https://github.com/eriktorsner/vagrant-wpskeleton/archive/master.zip
$ unzip master.zip
$ mv vagrant-wpskeleton-master/ casestudy1
$ rm -rf master.zip
$ cd casestudy1/

Navigate into the newly created folder casestudy1 and open the file Vagrantfile in your favorite text editor, you need to modify the four parameters in that file to suit this project (note that you might need to use a different IP depending on your Vagrant network settings):

 
# -*- mode: ruby -*-
# vi: set ft=ruby :

HOSTNAME = 'case1'
IPNUMBER = '192.168.50.38'
DEVDNS   = 'www.casestudy1.local'
TESTDNS  = 'test.casestudy1.local'

dir = Dir.pwd
require dir + '/vagrant/Vagrant'

Save the file and go back to the command line to type

$ vagrant up

This command might take a little while, up to 10 minutes is normal. First it will download the correct Ubuntu 14.04 LTS image and then it installs wp-cli, composer and some other tools. Once it’s finished, you can enter your newly created Vagrant machine:

$ vagrant ssh

 

Step 2: Install and configure WP Bootstrap

Note: From now on, unless stated otherwise, all bash commands shown should be executed from the /vagrant sub folder inside the virtual machine.

Once your inside the virtual machine, navigate to the /vagrant sub folder, install and initiate WP Bootstrap:

$ cd /vagrant
$ composer require eriktorsner/wp-bootstrap
$ vendor/bin/wpbootstrap wp-init-composer
$ composer wp-init

Note: The /vagrant sub folder inside the virtual machine is shared with the project folder on your normal hard drive, so you can edit files using your favorite text editor or IDE. This is one of the main advantages of using a Vagrant machine as development environment, you’ll use your standard set of tools to work with the code, but then the code runs inside a separate environment where you can install project specific things such as WP Bootstrap.

The last command above, wp-init, is a convenient command that creates template files for localsettings.json and appsettings.json. Those two files controls most of WP Bootstraps behavior so it’s nice get templates added. The file localsettings.json is used to keep settings that is specific to this machine, you’ll create a unique localsettings file for each different environment and you typically don’t want to maintain it in git. We need to edit localsettings.json to suit this machine and since we are using a standard Vagrant image we just use the mysql database created by default during the Vagrant provisioning. Edit localsettings.json:

{
	"environment": "development",
	"url": "www.casestudy1.local",
	"dbhost": "localhost",
	"dbname": "wordpress",
	"dbuser": "wordpress",
	"dbpass": "wordpress",
	"wpuser": "admin",
	"wppass": "admin",
	"wppath": "/vagrant/www/wordpress-default"
}

and appsettings.json to this:

{
	"title": "Case study 1"
}

Then we can get a very basic WordPress install up and running with a few commands:

$ composer wp-install
$ composer wp-setup

 

After a few minutes, you should be able to log in to your WordPress site using the url: http://www.casestudy1.local/wp-admin and login with username: admin and password: admin (don’t worry, your live site will not use these credentials, they are only used in development).

As a last preparation before moving on, we’re going to create a snapshot of what the WordPress options looks like right now for future reference using wp-cli. So before running the command, we’ll create a wp-cli settings file to reduce typing:

$ echo "path: /vagrant/www/wordpress-default" > wp-cli.yml
$ wp option list > opt.initial.snapshot

 

Step 3: Add plugins and a theme

This test site is going to use a free theme from the WordPress repository as well as a few free plugins. We’ll add them by editing appsettings.json and run the wp-setup command again. Open appsettings.json and change it to:

{
    "title": "Casestudy1",
    "themes": {
        "standard": ["vantage"],
        "local": ["vantage-child"],
        "active": "vantage-child"
    },
    "plugins": {
        "standard": [
            "ml-slider", "siteorigin-panels", "so-widgets-bundle",
            "wp-cfm"
        ]
    }
}

What does these things mean? Well, this json file contains different sections describing various aspects of the WordPress installation we’re creating:

  • title: This was added earlier and is simply the title for the WordPress site. This is the only mandatory property of appsettings.json since WordPress needs have a title to install and initialize. The other properties that are strictly needed, such as website url and admin username are defined in localsettings.json.
  • themes: this property is a json object with a few subproperties
    • standard: this is a list (array) of plugin slugs that will be installed from the WordPress standard theme repository. If you need, you can also specify a specific version using a colon, like this “vantate:1.0.2”
    • local: this is a list of themes that exist locally under “wp-content/themes” in your project folder. This is suitable if you’re using a premium theme that can’t be downloaded from the WordPress repo or as we’re going to do, use a local child-theme. The folder name needs to match the string supplied here, so for the above configuration, WP Bootstrap expects to find a folder named /path/to/your/project/wp-content/themes/vantage-child. Note that the folder will be sym-linked to the wp-content/themes folder in the actual WordPress installation (specified in localsettings.json).
    • active: a string that specifies the theme that should be activated, in this case, the child theme
  • plugins: This structure is very similar to the themes structure, but there isn’t any “active” property, all plugins are activated after install
    • standard: this is a list (array) of plugin slugs that will be installed from the WordPress standard plugin repository. If you need, you can also specify a version using a colon, like this “wp-cfm:1.0.2”. A URL to a zip file is also acceptable, this can be useful if you want to install a plugin directly from a git repo for instance
    • local: this is a list of plugins that exist locally under “wp-content/plugins” in your project folder. This is suitable if you’re using a premium plugin or plugins that you develop specifically for this particular site and that will be kept in git.

Before we can apply these settings to our WordPress installation, we need to create the child theme folder and place a minimal child theme in there.

$ mkdir -p wp-content/themes/vantage-child
$ touch wp-content/themes/vantage-child/style.css
$ touch wp-content/themes/vantage-child/functions.php

 

Open wp-content/themes/vantage-child/style.css in your favorite text editor and add the following content:

/*
 Theme Name:   Vantage-child
 Template:     vantage
*/

 

…and open wp-content/themes/vantage-child/functions.php and add the following:

<?php

add_action('wp_enqueue_scripts', 'theme_enqueue_styles');

function theme_enqueue_styles()
{
    wp_enqueue_style('parent-style', get_template_directory_uri().'/style.css');
    wp_enqueue_style('child-style', get_stylesheet_directory_uri().'/style.css', array('parent-style'));
}

 

Once both files are saved, we can go ahead and apply the changes using the command:

$ composer wp-setup

The first time this command runs, there’s not much output at all but it might take a minute or two depending on your Internet download speed. Once done, you can surf to http://www.casestudy1.local/ and you’ll see the Vantage theme default screen:

 

Vantage default look

Log in to the WordPress admin area and go to the plugins section, you should see that the plugins we specified in appsettings.json are all installed and activated:

List of plugins

 

At this point, we have created a WordPress site with the theme and plugins of our liking simply by creating a couple of configuration files,

  • composer.json used for installation of WP Bootstrap
  • localsettings.json that configures some server specific things like passwords and paths
  • appsettings.json than configures themes and plugins we want to use, both from the repo and local to our hard drive

So what we have done so far is to create a text file based configuration for installing WordPress and a couple of plugins, just in a format well suited for managing in Git.

Step 4: Creating content

For this step, we’re going to work mostly inside the WordPress admin area. We’re going to create a front page slider with the Meta Slider plugin and then set up a welcome page that uses that slider and some additional content.

Create the slider

Go to the Meta Slider settings and create a new slider and add a single image slide to it. The on screen instructions should be easy to follow, set the name “welcome” to the slider and set a caption for the image.

Meta slider

Create the Welcome page

Next, to go Pages->Add new to create a page. Give it the title “Welcome”.

Set a title

Select the Full Width Page template in the meta box on the right hand side. The theme we’ve selected has an option to select a Meta Slider as a page option and in that drop down, you should see the welcome-slider that we’ve just created. Then hit publish to save the page for the first time.

Selection_358

The next step is to add some content using Page builder. Add a row with 3 columns and add a text widget to each of them. Place some dummy text in them and Update the page. The Page Builder view on the edit page should look something like this:

Page builder

Next, we’ll head to Settings -> Reading in the WordPress admin area to make our new page the front page of the site:

Settings -> Reading

Click Save changes and then head to Appearance -> Theme Settings. Note that this is a menu option that is specific for this theme, so don’t expect to see this if you’re testing this with a different theme. We want to remove the default “Header text” and menus:

Vantage Theme Settings

Vantage Theme settings pt2

Scroll down to the settings page and click Save Settings. We can now have a look at the test website, it should look something like this:

Case study test site

 

Step 5: Exporting content

We’ve now got a reasonably standard WordPress site with some added content and modified settings. Our next task is to make some additions to appsettings.json so that it can export all the content we’re interested in. Options that we’ve changed in the WordPress admin area will be stored to disk by setting up the WP-CFM plugin and we’re also going to add two new sections to appsettings.json:

  • content: The content section lists post types and individual posts that we want to include in the export. We’ll also be listing some taxonomies.
  • references: The references section is when the content is imported back into a WordPress site. In various places in the content, there are data items that refer to posts or taxonomy terms by the internal ID. If we can successfully tell WP Bootstrap which settings to treat as references, the import process will be able to restore those references during import.

But lets start with WP-CFM. Go to Settings -> WP-CFM in the WordPress admin area and click Add Bundle.  Name the bundle wpbootstrap and click the Save button. You should now see a lot of unchecked boxes, each box representing an option that is stored in the wp_options table:

WP-CFM settings

Identifying exactly which options to include is a separate, and quite big, topic, for now, we’re just going to add the options that matters (the most) in this specific installation. Most options in the wp_options table just get a default value and in most cases, it’s perfectly OK to let the target WordPress installation (where we’lll eventually import these settings) to set it’s own default values. For this tutorial, we’re going to be as lean as possible and only include values that we really need, namely these three:

  • vantage_theme_settings All theme options that we edited in step 4 above are stored in this single option.
  • show_on_front This is the WordPress option that determines if the first page is a static page or a list of recent blog posts, we’ve changed this option so we need to include it.
  • page_on_front WordPress keeps track of the post ID of the page that is set as our front page, we’ve set the “Welcome” page as our front page, so this setting needs to be exported

 

Find and mark each of these options in the WP-CFM settings page and click save.

The next thing we’ll do is add what posts to include in the export. For this, we’ll edit appsettings.json directly. To figure out what pages (and post types) to include, we’re going to use wp-cli to display what our installation has. First of all, we want to include the welcome page. We could just be lazy and include all pages, or we can be explicit and only include the page we know we want. First, list all pages using wp-cli at the Vagrant command line:

$ wp post list --post_type=page
+----+-------------+-------------+---------------------+-------------+
| ID | post_title  | post_name   | post_date           | post_status |
+----+-------------+-------------+---------------------+-------------+
| 6  | Welcome     | welcome     | 2015-12-29 17:24:30 | publish     |
| 2  | Sample Page | sample-page | 2015-12-27 22:25:16 | publish     |
+----+-------------+-------------+---------------------+-------------+

We’re going to be explicit and only include the page we’ve worked with, so the resulting appsettings.json becomes:

{
    "title": "Casestudy 1",
    "themes": {
        "standard": ["vantage"],
        "local": ["vantage-child"],
        "active": "vantage-child"
    },
    "plugins": {
        "standard": [
            "ml-slider", "siteorigin-panels", "so-widgets-bundle",
            "wp-cfm"
        ]
    },
    "content": {
        "posts": {
            "page": ["welcome"]
        }
    }
}

For reference, if we had wanted to include all pages, we could have used:

// lazy: include all posts with post-type = page
"posts": {
    "page": "*"
}

 

The plugin Meta Slider stores it’s sliders as posts with custom post type ml-slider. To figure this out, we can see what post types this installation has:

$ wp post-type list
+---------------+-----------------------+-------------+--------------+--------+-----------------+
| name          | label                 | description | hierarchical | public | capability_type |
+---------------+-----------------------+-------------+--------------+--------+-----------------+
| post          | Posts                 |             |              | 1      | post            |
| page          | Pages                 |             | 1            | 1      | page            |
| attachment    | Media                 |             |              | 1      | post            |
| revision      | Revisions             |             |              |        | post            |
| nav_menu_item | Navigation Menu Items |             |              |        | post            |
| ml-slider     | Meta Slider           |             |              | 1      | post            |
+---------------+-----------------------+-------------+--------------+--------+-----------------+

 

If you know your way around WordPress, you should quickly see that the type ml-slider is non standard. Let’s see what posts we have with that type:

$ wp post list --post_type=ml-slider
+----+------------+------------+---------------------+-------------+
| ID | post_title | post_name  | post_date           | post_status |
+----+------------+------------+---------------------+-------------+
| 4  | welcome    | new-slider | 2015-12-29 17:14:12 | publish     |
+----+------------+------------+---------------------+-------------+

The only post with type ml-slider has title welcome and post_name=new_slider and this matches with how we named the slider we created in step 4. When we define what posts to include in an export, we want to use the post_name as the identifier, to adding the slider to the exported content:

{
    "title": "Casestudy 1",
    "themes": {
        "standard": ["vantage"],
        "local": ["vantage-child"],
        "active": "vantage-child"
    },
    "plugins": {
        "standard": [
            "ml-slider", "siteorigin-panels", "so-widgets-bundle",
            "wp-cfm"
        ]
    },
    "content": {
        "posts": {
            "page": ["welcome"]
            "ml-slider": ["new-slider"]
        }
    }
}

 

When we just add an image to a page or post, WP Bootstrap is usually able to identify what media files to include in the export because it can be figured out by analyzing the post itself. But in this case, the image we added to the slider is not really attached to the page, it rather “belongs” to the slider. Since any image could potentially be included to more than one slider, the authors of Meta Slider is using a taxonomy (special kind of category) to tie the image to a slider. Because of this WP Bootstrap can’t figure out that the image needs to be included and we need to include the image separately. Internally, media files are just posts with the post type attachment:

$ wp post list --post_type=attachment
+----+-------------+-------------+---------------------+-------------+
| ID | post_title  | post_name   | post_date           | post_status |
+----+-------------+-------------+---------------------+-------------+
| 5  | camera-1080 | camera-1080 | 2015-12-29 17:14:48 | inherit     |
+----+-------------+-------------+---------------------+-------------+

So we’re going to and add this single attachment to appsettings.json:

{
    "title": "Casestudy 1",
    "themes": {
        "standard": ["vantage"],
        "local": ["vantage-child"],
        "active": "vantage-child"
    },
    "plugins": {
        "standard": [
            "ml-slider", "siteorigin-panels", "so-widgets-bundle",
            "wp-cfm"
        ]
    },
    "content": {
        "posts": {
            "page": ["welcome"]
            "ml-slider": ["new-slider"],
            "attachment": ["camera-1080"]
        }
    }
}

As mentioned above, Meta Slider uses a taxonomy to tie the image to the slider, let’s look at what taxonomies we have:

$ wp taxonomy list
+---------------+------------------+-------------+---------------+---------------+--------------+--------+
| name          | label            | description | object_type   | show_tagcloud | hierarchical | public |
+---------------+------------------+-------------+---------------+---------------+--------------+--------+
| category      | Categories       |             | post          | 1             | 1            | 1      |
| post_tag      | Tags             |             | post          | 1             |              | 1      |
| nav_menu      | Navigation Menus |             | nav_menu_item |               |              |        |
| link_category | Link Categories  |             | link          | 1             |              |        |
| post_format   | Format           |             | post          |               |              | 1      |
| ml-slider     | Categories       |             | attachment    |               | 1            |        |
+---------------+------------------+-------------+---------------+---------------+--------------+--------+

Again, if you know your way around WordPress, you’ll notice that the ml-slider taxonomy is a non standard taxonomy and it also say that it’s linking to object_type=attachment, so we know that’s the one we need to export. Normally when we add taxonomies to the WP Bootstrap appsettings.json, we can just specify it’s name like this if we want to export all terms in a taxonomy:

{
    "title": "Casestudy 1",
    "themes": {
        "standard": ["vantage"],
        "local": ["vantage-child"],
        "active": "vantage-child"
    },

    "plugins": {
        "standard": [
            "ml-slider", "siteorigin-panels", "so-widgets-bundle",
            "wp-cfm"
        ]
    },
    "content": {
        "posts": {
            "page": ["welcome"],
            "ml-slider": ["new-slider"],
            "attachment": ["glasses_coffee"]
        },
        "taxonomies": {
            "ml-slider": "*"
        }
    }
}

The above would cause WP Bootstrap to include any term in the taxonomy “ml-slider” in the export. During import, the taxonomy would be imported with it’s slug as the unique identifier. If a taxonomy term already exists with the same slug, WP Bootstrap would update that term, but if it didn’t exist, WP Bootstrap would create it. However, Meta Slider taxonomies are a little different. When a slider is created, a new taxonomy term is created with the slide post id as the name and slug. We saw above that our slider had post id = 4, so Meta Slider would have created a term with the name/slug = 4. This presents a little problem during import because there’s no guarantee that the slider will get id=4 on the target site so a taxonomy term with the name/slug 4 would be useless. We need to instruct WP Bootstrap to treat this taxonomy a little different. Instead of specifying an asterisk (string) or an array similar to the posts, we’re specifying it as an object with some properties, like this:

    "taxonomies": {
        "ml-slider": {
            "type": "postid",
            "termDescriptor": "*"
        }
    }

The resulting appsettings.json now becomes:

{
    "title": "Casestudy 1",
    "themes": {
        "standard": ["vantage"],
        "local": ["vantage-child"],
        "active": "vantage-child"
    },

    "plugins": {
        "standard": [
            "ml-slider", "siteorigin-panels", "so-widgets-bundle",
            "wp-cfm"
        ]
    },
    "content": {
        "posts": {
            "page": ["welcome"],
            "ml-slider": ["new-slider"],
            "attachment": ["glasses_coffee"]
        },
        "taxonomies": {
            "ml-slider": {
                "type": "postid",
                "terms": "*"
            }
        }
    }
}

 

Now, we have one last thing to do before we’re finished with appsettings.json and that is to define references. There are two post references in this site that matters, but we only need to take one of them into account. The first one is the page_on_front setting that we mentioned earlier. Since this is a standard WordPress setting, WP Bootstrap is already aware of it and we don’t need to specify it. The second one is slightly trickier, the welcome page has a reference to the ml-slider post. Since Vantage theme lets us specify what slider to use on a page as a separate setting, there’s bound to be a reference to it somewhere and it’s by definition a reference to a post (we already know that a slider is just a post with post type “ml-slider”). To figure out the name of this setting, go to the WordPress admin area to edit the Welcome page. At the top of the screen, you can enable to see custom fields by clicking the Screen options and marking the correct checkbox:

Showing custom fields

Scroll down the page to the custom fields section, now we’re able to see all custom fields on this post.

custom fields

As you can see, there’s a field named “vantage_metaslider_slider” that has the value “meta:4”. This is a row in the WordPress table wp_postmeta with a reference to the ml-slider post with id=4. To add this to our appsettings.json, we need to add a references section:

{
    "title": "Casestudy 1",
    "themes": {
        "standard": ["vantage"],
        "local": ["vantage-child"],
        "active": "vantage-child"
    },
    "plugins": {
        "standard": [
            "ml-slider", "siteorigin-panels", "so-widgets-bundle",
            "wp-cfm"
        ]
    },
    "content": {
        "posts": {
            "page": ["welcome"],
            "ml-slider": ["new-slider"],
            "attachment": ["glasses_coffee"]
        },
        "taxonomies": {
            "ml-slider": {
                "type": "postid",
                "termDescriptor": "*"
            }
        }
    },
    "references": {
        "posts": {
            "postmeta": ["vantage_metaslider_slider"]
        }
    }
}

There are a few ways to add information about references to WP Bootstrap, in this case we’re telling WP Bootstrap that there is a postmeta field named “vantage_metaslider_slider” and that it points to a post. We’re basically telling WP Bootstrap that whenever it comes across a postmeta field with this name, it contains an integer that’s a reference to a post id. During import, WP Bootstrap should look up what id that post has in the new site and change the value so that it points to the correct post id. We also saw that the content of this field was not an integer but a string (meta:4). WP Bootstrap can handle this fine just as long as the string doesn’t get too complicated.

With that last piece in place, we’re all done with appsettings.json and can perform the actual export:

$ composer wp-export

You now have a file based representation of your WordPress site in the sub folder bootstrap/ with the following structure:

bootstrap/
├── config/
├── manifest.json
├── media/
|   ├── camera-1080/
├── posts/
│   ├── attachment/
│   ├── ml-slider/
│   └── page/
└── taxonomies/
    └── ml-slider

Together with the appsettings.json file and the projects wp-content folder,  the bootstrap folder is all you need to check in to keep this site managed under Git. Using a workflow combining git commands and WP Bootstrap the relevant parts of the WordPress site can be migrated to a staging or production environment with ease. References between WordPress objects will be preserved on import. When importing this content to another WordPress installation, WP Bootstrap will not touch anything that’s not defined or described in the data we’re bringing, any other posts, pages, comments that exist on the target installation will remain untouched which is the whole point with WP Bootstrap.

Step 6: Putting it to the test

Since we now have a file based representation of our site we’re able to put WP Bootstrap to the test. Let’s destroy the actual site and try the wp-import command. If we’ve gotten everything correct, we should get our site back just as it looked before we destroyed it.

To begin with, WP Bootstrap has a command to completely wipe a WordPress installation, since it’s a bit dangerous it’s not automatically mapped as a composer script. Instead, we need to call the wpbootstrap binary directly:

$ vendor/bin/wpbootstrap wp-reset

This will command will drop all the WordPress tables from the database and forefully delete every single file in the WordPress folder defined in localsettings.json. Powerful but dangerous. Surf to http://www.casestudy1.local/ just to verify that your WordPress installation is indeed gone, you should see a 403 Forbidden message from Nginx.

Next, run the commands to install WordPress, set it up with the right theme and plugins and lastly import content and settings again.

$ composer wp-install
$ composer wp-setup
$ composer wp-import

After these three commands, go back and check http://www.casestudy1.local/ again, your WordPress installation should be back as it were before it was deleted. If you want to play around with WP Bootstrap a bit, an interesting exercise is to reset the installation, run wp-install and wp-setup  to get it back. But before the wp-import command, go ahead and add some pages and posts to make sure the database id’s on the imported posts are different than they were in the initial install.

Conclusions and next steps

Creating a site using WP Bootstrap requires some additional steps compared to the WordPress famous 5 minute install even if it should still be quite possible to do it in under 5 minutes. But the major benefit of using this method is not so that time can be saved at first install but at the long term advantages you’ll get. Now we have a WordPress site that can be installed and configured using a few commands at the terminal, even if that’s been possible to do using wp-cli alone for quite some time, we’re also managing the (important) content. And the content itself is in a format that is suitable for Git and contains just enough meta data for it to be portable between WordPress installations. It’s the foundation for a solid workflow.

The next natural step to go to from here is to add your website to a Git repository.  First, we need to create a .gitignore file with (at least) the following:

.vagrant/
vendor/
www/
localsettings.json

 

Then the following files and folders should be added to Git:

bootstrap/
wp-content/
.gitingore
appsettings.json
composer.json

 

After checkout in the staging or production environment, you can create the initial site using:

$ composer update
$ composer wp-install
$ composer wp-setup
$ composer wp-import

 

When making changes to the original Vagrant installation (your development environment), you check in all changes to git, then back in the staging or production environment, you’d just perform a few commands to get all the changes:

$ git pull
$ composer wp-setup
$ composer wp-import

 

A final note

WP Bootstrap is currently at version 0.3.1, a lot of features are already implemented, but bugs exist and a lot of features simply aren’t implemented yet. If you decide to use WP Bootstrap in a production environment, it’s because you are an early adopter and are prepared to spend lots of time fix potentially large and complicated issues manually. If you don’t feel like an early adopter or if you can’t risk to mess up a deployment, please refrain from using WP Bootstrap in production environment until the package is a bit more mature.

Questions? Concerns? Angry? Happy? Let me know in the comments section below.

WordPress configuration management

This is the 4th post in a series of developing for WordPress in a DevOps friendly way. The other articles:

  1. Introduction to WordPress and DevOps
  2. Developing with WordPress and Vagrant
  3. Grunt Automation for WordPress developer
  4. WordPress configuration management

In the previous posts in this series we’ve been looking at how to work with Vagrant and WordPress and how to automate setup work using Grunt and WP-CLI. In this posts, we’ll look a little bit on how we can transfer various settings between the WordPress database and into text files in the source code tree. Because as soon as we have the settings in files, we can easily transfer those settings to a target system such as a staging environment or the live site.

There’s a Git repository available with code for this post here: https://github.com/eriktorsner/wpconfigurationmanagement I suggest you clone or download the code to your development computer to make it easier to follow along.

WordPress settings

A Setting is any of the small or large things you change in the Settings menu in the WordPress admin area. The number of blog posts shown on the first page is a setting and so is the site title and the default date format.

Settings
Some of the well known settings from the WordPress admin area

 

WordPress uses the database to store settings into a table named wp_options (at least as long as you are using the standard wp_ prefix). Most of the settings that a core WordPress installation will put into the wp_options table are simple scalar values, a string or a numeric value. But some of the settings consists of larger more complex structs like an array or even arrays containing objects containing arrays. The internal WordPress code makes sure that pretty much anything you can represent in a PHP variable can be stored as a setting. If needed, WordPress uses the native PHP function serialize() to convert any given variable to a text representation suitable for database storage and then unserialize() to convert it back when needed.

Serializing

The concept of taking a complex structure and transforming it into a text representation is called seriallization, so no wonder the PHP functions are named as they are. In our ambitions to automate the setup of WordPress, we want to serialize some settings to a text file that we can keep in our source code repository. When we first install a development version of our WordPress site in a new environment, or when we want to deploy it to another environment, we want to take that text file with serialized settings and update the database. To do this we will continue to build on the WordPress skeleton from the previous posts, you’ll find it in the Github repository for this post. To get started with this code repository, please refer to the first post to learn a little bit about Vagrant and how we’re using it. A few notes:

  • This repo uses an evolved version of the Vagrantfile. Only the rows you need to change are present, everything else is moved in to a file in the vagrant/ sub folder.
  • No need to change anytning inside the vagrant/ sub folder, everything it’s taken care of during provisioning.

 We’re going to talk about two different approaches for managing settings in a text file. The first approach is using Gruntfile.js itself, the other approach uses the free plugin WP-CFM.

Keeping settings in Gruntfile.js

The most straight forward way would be to use Gruntfile and Wp-cli. The settings themselves will be in the form of Wp-cli statements that will be automatically inserted into the target WordPress installation when the Grunt task wp-setup is executed.


grunt.registerTask('wp-setup', '', function() {
	ls = getLocalsettings();
	wpcmd = 'wp --path=' + ls.wppath + ' --allow-root ';
	
	// some standard plugins
	stdplugins = ['google-analyticator', 'wp-cfm'];
	for(i=0;i<stdplugins.length;i++) {
		name = stdplugins[i];		
		shell.exec(wpcmd + 'plugin install --activate ' + name);
	}

	shell.exec(wpcmd + 'option update blogname "New blog title"');
	shell.exec(wpcmd + 'option update blogdescription "experimental tagline"');
	shell.exec(wpcmd + 'option update posts_per_page "20"');

})

The three highlighted rows will update the Site title (blogname), the tag line (blogdescription) and the ‘Blog pages show at most’ setting (posts_per_page) that are found in WordPress Admin. This is a very manual form of serializing settings to disk and it’s easy to get started with. If you only have a few of them that you need to set, this approach will work but it has a few downsides.

Obviously, the manual work involved in writing the wp-cli statements in your Grunt file is not very optimal. Easy to forget individual settings, easy to lose the overview etc. The other downside is that changes you make in WordPress admin has no way of automatically find their way into the Gruntfile. You’re in for a lot of manual work. But there is another way.

WP-CFM

WP-CFM is a free plugin available in the WordPress plugin repository. It’s name stands for WordPress Configuration Management and it does exactly that: Configuration Management. WP-CFM uses a concept call bundels. A bundle is a group of individual WordPress settings. WP-CFM can Push a bundle to file, meaning that it will read the value of each of the settings in the bundle from the database and store them in a file. And later, WP-CFM can Pull that file back in and restore those values in the database.

In the Gruntfile above I took the liberty of installing and activating wp-cfm in the WordPress installation in the Vagrant box, so if you’re following along you should already have it in WordPress. This plugin adds a menu item under settings named WP-CFM. The main WP-CFM screen looks like this:

WP-CFM admin screen

We want to create a bundle with the same three setting that we handled in the Grunt task above. So we’ll go ahead and click ‘Add Bundle’, name it ‘settings’ and select the individual settings items we need:

Creating a new bundle in WP-CFM
Creating a new bundle in WP-CFM (note, the posts_per_page setting is under the fold in this image)

After the bundle is created and saved, we can click ‘Push’ to store those three settings to disk. You should end up with a text file in /vagrant/www/wordpress-default/wp-content/config named settings.json:

{
    "blogdescription": "experimental tagline",
    "blogname": "New blog title",
    "posts_per_page": "20",
    ".label": "settings";
}

As you can see, WP-CFM uses a JSON file to store the individual values and stores the file in a predictable location. For fun, we can change the “blogname” setting inside this file and try the Pull button (you probably will need to reload the page for the Pull button to become active). Once the updated settings has been pulled into the database and you’ve reloaded the page, you should see that whatever value you selected for “blogname” now is in the page title.

A little automation

The one great thing with WP-CFM that I didn’t mention yet is that it was written with support for Wp-cli right out of the box. WP-CFM adds a command verb to Wp-cli named ‘config’ with sub commands push and pull. We just need to call these two commands from our Gruntfile to automate things. As usual,  a little bit of plumbing is also needed as well, best explained with code, so let’s have a look at the two new Grunt tasks that we’ve added for this post:


grunt.registerTask('wp-export', '', function() {
	ls = getLocalsettings();
	wpcmd = 'wp --path=' + ls.wppath + ' --allow-root ';
	pwd = shell.pwd();

	shell.mkdir('-p', pwd + '/config');

	// push settings from DB to file
	src = ls.wppath + '/wp-content/config/settings.json';
	trg = pwd + '/config/settings.json';
	shell.exec(wpcmd + 'config push settings');
	shell.cp('-f', src, trg);
});

grunt.registerTask('wp-import', '', function() {
	ls = getLocalsettings();
	wpcmd = 'wp --path=' + ls.wppath + ' --allow-root ';
	pwd = shell.pwd();

	shell.mkdir('-p', ls.wppath + '/wp-content/config');
	
	src = pwd + '/config/settings.json';
	trg = ls.wppath + '/wp-content/config/settings.json';
	shell.cp('-f', src, trg);
	shell.exec(wpcmd + 'config pull settings');
});

  • Line 53, define the task wp-export
  • Line 58, create the /vagrant/config folder unless it already exists
  • Line 63, run the wp-cli command ‘config push’ for the bundle named ‘settings’
  • Line 64, copy the settings file into our local folder /vagrant/config where it will be under source code control

 

  • Line 67, define the taks wp-import
  • Line 72, create the folder www/wordpress-default/wp-content/config unless it already exists
  • Line 76, copy the settings.json file from the project folder into the correct folder in the WordPress installation (where WP-CFM will expect to find it)
  • Line 77, run the wp-cli command ‘config pull’ for the bundle named settings so that each settings is pulled from the file into the database

Since the WP-CFM plugin was build for automation from the start, our work is reduced to managing the settings file so that we can keep in under source code control. With these two Grunt tasks, we’ve now automated the process for storing WordPress settings in the source code control system.

A few pitfalls

Using WP-CFM together with Grunt and wp-cli takes us a long way in terms of creating a fully automated process for managing WordPress.  However, this process isn’t really perfect yet. There are a few issues to look out for when it comes to WP-CFM:

  • Some settings might store the absolute URL for a post or page on the WordPress installation. If that setting is pulled from disk to the database unchanged, the live site might end up with URL references to the development version of the site
  • Some settings contains references to a page, a post or a menu item using the internal database id and the database ID might differ between the development version and the production version.

These two issues as well as the challenge of moving actual content (pages, images etc) from development to production is going to be covered in future posts in this series. So stay tuned!

 

WordPress DevOps – The book

I’ve written an ebook on this subject. Released in September this year on Leanpub.com. Expect a 100+ tightly written pages where we walk through the creation of the skeleton of a WordPress based Saas application, connected to Stripe and Paypal with a working deployment process that takes content into account. Just add your billion dollar idea. Jump on over to Leanpub to get your copy.

WordPress DevOps - Strategies for developing and deploying with WordPress
WordPress DevOps – Strategies for developing and deploying with WordPress

 

 

 

 

 

 

 

[wysija_form id=”3″]

Grunt Automation for WordPress developers

This is the third article in a series of developing for WordPress in a DevOps friendly way. The previous articles:

  1. Introduction to WordPress and DevOps
  2. Developing with WordPress and Vagrant
  3. Grunt Automation for WordPress developers
  4. WordPress configuration management

In the previous two posts we’ve had a look at the various tools we need to create an automated workflow for developing and a little bit about how Vagrant can be used to create a better development environment. We’ve also briefly touched on using Grunt and wp-cli to automate setting up WordPress inside the environment. In this post we’ll dive deeper into how to use Grunt to automate even more of the WordPress setup.

There’s a Git repository available with code for this post here: https://github.com/eriktorsner/gruntautomationforwp I suggest you clone or download the code to your development computer to make it easier to follow along.

What’s our goal?

In short. We want to run a single command at the command line to install WordPress, all our wanted plugins and other vital pieces of configuration. The end goal is to automate it to the extent that it can be part of a fully automated, non-interactive, deployment process.

Looking back at the first post in this series I talked a bit about DevOps and how it’s a bit of a challenge to make WordPress a good fit for it. Automation is one of the cornerstones within DevOps and historically WordPress has been more focused on getting up and running quick than on supporting an automated workflow.

Well, that changed entirely when wp-cli came onto the scene a few years back. Wp-cli stands for WordPress command line interface and is a project that aims to enable automation of WordPress management. Wp-cli makes it possible to automate installation, setup, theme and plugin installations and a lot of other common WordPress management tasks like modify settings or even add pages and posts.

The other part of the automation work will be carried out by Grunt. Grunt is a “modern JavaScript task runner” and allows us to create tasks that can be executed from the command line. So we can create a task “wp-install” that uses wp-cli to install WordPress and run that task from the command line using a simple “grunt wp-install”. The most common use case for Grunt is to run things like css and javascript minification or compile SASS file to css. But we’ll use Grunt mainly as a task runner for DevOps related tasks. That doesn’t stop you from using Grunt for those other things as well which may be a very good idea for your project.

Creating the environment

In the previous post, we covered how to get started with Vagrant. To follow along in this post I’m assuming that you’ve read that post and have installed the prerequisites for running Vagrant on your development computer. I’ve made a separate Github repository available for this post, so from now on when I’m talking about specific files, I’m referring to the ones you can find in the git repo at https://github.com/eriktorsner/gruntautomationforwp. If you have any problems following these steps, be sure to read up on the previous post and post any questions in the comments below if you’re still having issues.

A quick checklist to get you started with this Vagrant box

  1. Edit Vagrantfile (hostname, dns names and ip-numner) to fit in your environment
  2. copy localsettings.json.template to localsettings.json
  3. Run “vagrant up” to initialize the new machine”
  4. Go to folder /vagrant inside the virtual machine and run “npm install”

Wp-cli + Grunt

To show what Wp-cli can do in terms of automation, we’ll use it to perform the following tasks:

  1. Install WordPress
  2. Install and activate a few plugins from the official WordPress repo
  3. Change a few settings

As we’ll be doing this by automating wp-cli via Grunt. Let’s have a look at the important parts of the Grunt file that comes with this post (see the top of the post for information on how to get it). The first thing to notice is on 32 where we define the function getLocalSettings, a simple helper function.


function getLocalsettings(test) { 
    ls = grunt.file.readJSON('localsettings.json'); 
    if(ls.wppath === undefined) ls.wppath = shell.pwd() + '/www/wordpress-default'; 
    return ls; 
}

We’ll use this function in each of our Grunt tasks that deals with wp-cli so that we can get the parameters we define in localsettings.json into action. Let’s look at the settings file to get a hunch of what kind of parameters we’re including


{
    "environment": "development",
    "url": "www.gruntautomationforwp.local",
    "dbhost": "localhost",
    "dbname": "wordpress",
    "dbuser": "wordpress",
    "dbpass": "wordpress",
    "wpuser": "admin",
    "wppass": "admin",
    "wppath": "/vagrant/www/wordpress-default"
}

 

The idea is to have anything that is specific for this specific machine should be a parameter in this file. And the point of having settings in a json format is that json can be easily accessed both from javascript code like in the Gruntfile and in PHP code as well.

Let’s look at the first task defined, the default task:


grunt.registerTask('default', 'Log some stuff.', function() {
    ls = getLocalsettings();
    grunt.log.write('localsettings successfully read URL=' + ls.url).ok();
});

It will simply read the settings file and output the URL parameter from it, so it’s a simple test. Let’s try it within the Vagrant machine:

$ cd /vagrant
$ grunt
Running "default" task
localsettings successfully read URL=www.gruntautomationforwp.localOK

Done, without errors.

The next task to look at is the wp-install task, it’s a bit more interesting:

 /*
 * Installing WP
 */
 grunt.registerTask('wp-install', '', function() {
     ls = getLocalsettings();
     wpcmd = 'wp --path=' + ls.wppath + ' --allow-root ';

     shell.mkdir('-p', ls.wppath);

     if(!shell.test('-e', ls.wppath + '/wp-config.php')) {
         shell.exec(wpcmd + 'core download --force');
         shell.exec(wpcmd + 'core config --dbname=' + ls.dbname + ' --   dbuser=' + ls.dbuser + ' --dbpass=' + ls.dbpass + ' --quiet');
         shell.exec(wpcmd + 'core install --url=' + ls.url + ' --title="WordPress App" --admin_name=' + ls.wpuser + ' --admin_email="admin@local.dev" --admin_password="' + ls.wppass + '"');
     } else {
         grunt.log.write('Wordpress is already installed').ok();
     }
 });
  • Line 18 is just loading the localsettings as we saw above
  • Line 19 creates the base string for the wp-cli command. Note that we’re adding the switch –allow-root since this task is likely to be executed by root in a different environment like production. We’re also adding the –path switch which will instruct wp-cli to install WordPress in a sub folder.
  • In line 23 we’re checking if WordPress is already installed or not.
  • Lines 24 to 26 are executing the wp-cli commands “core download”, “core config” and “core install”.

There are a few interesting things to note. The first is obviously that after running this task we’re going to have a fully functioning WordPress installation in a sub folder. All parameters we needed are kept in a separate file which is fundamentally good for our efforts to make this a fully automated WordPress install. We’ve also managed to install WordPress in a sub folder that is explicitly kept out of source code control.

The reason for that is that WordPress in not our code, it’s a depencency to us. We want to avoid adding dependencies in our source code tree (look inside .gitignore, we’re explicitly ignoring the www sub folder) for several reasons. But the most important reason is not size or bloat, it’s the ability to handle upgrades well. WordPress and it’s extensions are upgraded frequently with major and minor upgrades. If you add all the source code for WordPress, themes and plugins into your own source code tree, you will be stuck with the task of upgrading them once new versions arrive, and they do quite often.

A clean separation between your own code and the dependencies means that you can easily test your code with the newest versions of each dependency. If your code breaks as a result of upgrading one of the third party plugins, the clean separation and automated setup makes it super easy to test and fix any such problems before you upgrade anything in production. That’s a big deal.

So, back to our example, let’s run the wp-install task:

$ grunt wp-install
Running "wp-install" task
Downloading WordPress 4.3.1 (en_US)...
Success: WordPress downloaded.
sh: 1: /usr/sbin/sendmail: not found
Success: WordPress installed successfully.

Adding more dependencies

Obviously, we’re going to need more dependencies. Let’s add a few plugins from the WordPress plugin repository. This is done with the wp-cli command “plugin install”. Let’s look at the next task in Gruntfile.js:

/*
* Setting up WP
* 
*/
grunt.registerTask('wp-setup', '', function() {
    ls = getLocalsettings();
    wpcmd = 'wp --path=' + ls.wppath + ' --allow-root ';
	
    // some standard plugins
    stdplugins = ['if-menu', 'baw-login-logout-menu','google-analyticator'];
    for(i=0;i<stdplugins.length;i++) {
        name = stdplugins[i];		
        shell.exec(wpcmd + 'plugin install --activate ' + name);
    }
})
  • Lines 37-38 are similar to the wp-install task
  • Line 41 sets up an array of plugins we want to install
  • Lines 42-45 iterates that array and creates a wp-cli command that installs and activates all the plugins in the array.

So no more manual plugin installations in the WordPress admin area! Let’s run the Grunt wp-setup task:

$ grunt wp-setup
Running "wp-setup" task
Installing If Menu (0.3)
Downloading install package from https://downloads.wordpress.org/plugin/if-menu.zip...
Unpacking the package...
Installing the plugin...
Plugin installed successfully.
Success: Translations updates are not needed for the 'English (US)' locale.
Activating 'if-menu'...
Success: Plugin 'if-menu' activated.
Installing Login Logout Menu (1.3.3)
Downloading install package from https://downloads.wordpress.org/plugin/baw-login-logout-menu.zip...
Unpacking the package...
Installing the plugin...
Plugin installed successfully.
Success: Translations updates are not needed for the 'English (US)' locale.
Activating 'baw-login-logout-menu'...
Success: Plugin 'baw-login-logout-menu' activated.
Installing Google Analyticator (6.4.9.6)
Downloading install package from https://downloads.wordpress.org/plugin/google-analyticator.6.4.9.6.zip...
Unpacking the package...
Installing the plugin...
Plugin installed successfully.
Success: Translations updates are not needed for the 'English (US)' locale.
Activating 'google-analyticator'...
Success: Plugin 'google-analyticator' activated.

Done, without errors.

Working with settings

The last part I’m going to cover in this post is a little bit on how to manipulate WordPress settings. Wp-cli is not the only option we have to get settings from a text file (code) into a live WordPress installation, but since wp-cli can do this, let’s have a look at how.

Most settings in WordPress are stored in a table named wp_options (assuming you’ve kept the standard “wp_” table name prefix). In order to change any of those settings via wp-cli, we first need to figure out what the various settings are called. Wp-cli have a sub command “option” that lets us list, add, delete or modify settings. For instance, if we want to change the settings “Site title” and “Tagline” we could use wp-cli to list all options and search for the options we want to find. In the wp-install task, we set the string “WordPress App” as the title, lets search for it:

$ cd /vagrant/www/wordpress-default/
$ wp option list | grep 'WordPress App'
blogname	WordPress App

Ok, there’s only one single row in the options table with that string, so we can safely assume that the option called “blogname” corresponds to Site title. Let’s look for the tagline, we haven’t changed it yet in our test installation, so it should still read “Just another WordPress site”:

$ wp option list | grep 'ust another WordPress site'
blogdescription	Just another WordPress site

Right. The parameter tagline that we can control in the WordPress admin is found in the option named “blogdescription”.

Knowing what the options are called makes it possible to set them via wp-cli. We can add a few lines to the wp-setup task:

    shell.exec(wpcmd + 'option update blogname "Another title"');
    shell.exec(wpcmd + 'option update blogdescription "experimental tagline");

Running the wp-setup task again, we should now see:

$ grunt wp-setup
Running "wp-setup" task
Warning: if-menu: Plugin already installed.
Activating 'if-menu'...
Warning: Plugin 'if-menu' is already active.
Warning: baw-login-logout-menu: Plugin already installed.
Activating 'baw-login-logout-menu'...
Warning: Plugin 'baw-login-logout-menu' is already active.
Warning: google-analyticator: Plugin already installed.
Activating 'google-analyticator'...
Warning: Plugin 'google-analyticator' is already active.
Success: Updated 'blogname' option.
Success: Updated 'blogdescription' option.

Done, without errors.

Note that wp-cli won’t attempt to reinstall the plugins that are already activated but instead just sends a warning saying that it’s already there. The last few lines tells us that the blogname and blogdescription settings are now updated to their new values. Mission accomplished.

 

Summary

In this post, we’ve taken another few steps towards gettings WordPress under our control. We’ve discussed the reasons why we want to treat WordPress itself as well as any third party extensions as dependencies rather than a part of our own application. Not in the sense that the code we develop would work well without WordPress and the plugins, but because we need to keep them out of our code base for upgrading and testing reasons.

In future installments in this series, we’ll dive into dealing with content and try to find ways to make WordPress separate content and content. If that sounds weird or if you’re just the curious anyway, stay tuned for the next episode. In the mean time, share insights, questions or other feedback in the comments below.

WordPress DevOps – The book

I’ve written an ebook on this subject. Released in September this year on Leanpub.com. Expect a 100+ tightly written pages where we walk through the creation of the skeleton of a WordPress based Saas application, connected to Stripe and Paypal with a working deployment process that takes content into account. Just add your billion dollar idea. Jump on over to Leanpub to get your copy.

WordPress DevOps - Strategies for developing and deploying with WordPress
WordPress DevOps – Strategies for developing and deploying with WordPress

 

 

 

 

 

 

 

[wysija_form id=”3″]