Fantastic hooks and where to use them.

This post is an introduction to the useDispatch and useSelect hooks in the api found in the WordPress Gutenberg plugin. Note: the hooks will be available with the next release of the @wordpress/data package (which will happen after Gutenberg 5.9 is released)

So you’ve had a chance to finally figure out the api. You’ve written a few components using withSelect or withDispatch. You think you’ve got a handle on some of the finer points of higher order components in Gutenberg (and realize that’s essentially what withSelect or withDispatch are!). But now you start seeing things like useDispatch or useSelect pop up in use. What the heck are these? Where did they come from? Is everything you learned useless?

To answer the last question and appease your worries. No. Everything you’ve learned in using withSelect and withDispatch is still awesome. You can keep using them and your Gutenberg blocks and apps will still keep on rocking.

However, I want to take this opportunity to introduce you to a couple new friends in the Gutenberg space: useSelect and useDispatch.

Where’d they come from?

It probably doesn’t come as a surprise to most people who have done any development integrating with Gutenberg that it is primarily built using React. A significant new pattern to emerge in the react ecosystem in the last year is something known as React Hooks. Not to be confused with the WordPress hook system, in the words of the React Docs, hooks:

…let you use state and other React features without writing a class. docs

Essentially react hooks allow you more direct access to the React API in functional components. There’s some great documentation and tutorials out there on react hooks – I highly recommend the following:

One of the really interesting things about the react hooks api is that it introduces the ability to write custom hooks encapsulating common behaviour to use across multiple functional components. Essentially this is what useSelect and useDispatch are, custom hooks encapsulating logic for getting and setting data (or dispatching actions) in registered stores.

Where to use them

from withSelect to useSelect

To refresh our memory, withSelect is a higher order component you use to wrap a component so you can inject state driven props into it using registered selectors in a store.

So for example, let’s say you’ve created an app that displays some products you have and their prices. In this app, you’d probably have some sort of ProductWithPrice component that displays the price.

const ProductWithPrice = ( { product } ) => {
	return <div>
		<span className="product-name">{ }</span>
<span className="product-price">{ product.price }</span>

This is great, and in most cases would work just fine if the provided product always has a static price associated with it. But let’s imagine for a moment that the store using this app has prices that are more dynamic because they depend on either the location of the customer using the app, or the number of other items in the cart etc. So you decide to move the price for products to a custom data store. Now you might do something like this:

const { select } =;

const ProductWithPrice = ( { product } ) => {
	const price = select( 'inventory' ).getPrice( );
	return <div>
		<span className="product-name">{ }</span><span className="product-price">{ price }</span>

On the surface this seems to make sense. However, there’s a few problems with it:

  • select is imported from the default registry, which may not necessarily be the registry in this components related tree. Why this is a potential issue is something for another article so I won’t expand on that here.
  • The price for the product will only get updated if the component remounts. If the product prop never changes, then the latest price will not be shown.
  • If the price is retrieved via a REST api call (as opposed to in app changes updating state), then the initial mount of the component will have a value of undefined for the product price.

Let’s attempt a fix for the last two issues. Using familiarity with react lifecycle methods and the api, you might come up with something like this:

const { select, subscribe } =;
const { __ } = wp.i18n;
const { Component } = wp.element;

class ProductWithPrice extends Component {
	constructor( props ) {
		super( props );
		this.state = {
			price: __( '...retrieving' ),
		this.unsubscribe = () => {};

	updatePrice( price ) {
		this.setState( { price } );

	componentDidMount() {
		this.unsubscribe = subscribe( () => {
			const newPrice = select( 'inventory' )
				.getPrice( );
			if ( newPrice !== this.state.price ) {
				this.updatePrice( newPrice );
		} );

	componentWillUnmount() {

	render() {
		return <div>
			<span className="product-name">{ }</span>
			<span className="product-price">{ this.state.price }</span>

Oh wow, things just jumped up in complexity didn’t it? Yes, it did.

While it solves the issues with a stale price (price now get’s updated anytime it changes in the store state), and also handles if price is retrieved via REST api (via a selector with a resolver), it still doesn’t address the the tight coupling to the default registry (and now we have both select and subscribe being used from the default registry). Not only that, but what if we have other components that need the up-to-date price for a given product? Ugh, we’d have to repeat this logic in all those other components.

This is where withSelect came to the rescue. Here’s our ProductPrice component implemented using withSelect:

const { withSelect } =;
const { __ } = wp.i18n;

const ProductWithPrice = ( { product, price } ) => {
 return <div>
  <span className="product-name">{ }</span>
  <span className="product-price">{ price }</span>

export default withSelect( ( select, { product } ) => {
 return {
  price: select( 'inventory' ).getPrice( ) || __( '...retrieving' ),
} )( ProductWithPrice );

Things got a bit less complex again didn’t they? withSelect essentially takes care of all the boilerplate you need to add (subscriptions, state change etc) you saw in the previous example and exposes just the things you declare via the mapSelectToProps callback you provided to withSelect. On top of that, withSelect will always expose the select function from the registry exposed in context with the component being used (eliminating the first problem we had in the first example).

So finally, we’ve got an api that makes it relatively easy to interact with the inventory store. Still, let’s take a look at what things look like when we implement the new useSelect hook!

const { useSelect } =;
const { __ } = wp.i18n;

const ProductWithPrice = ( { product } ) => {
	const { price = __( '...retrieving' ) } = useSelect( ( select ) => {
		return select( 'inventory' ).getPrice( );
	}, [ ] );
	return <div>
		<span className="product-name">{ }</span>
		<span className="product-price">{ price }</span>

We’ve moved back towards the apparent simplicity of the original example didn’t we? One advantage of using hooks is that similar to rendering, it allows you to write code that declares what happens at all points of time simultaneously. Like withSelect, useSelect abstracts away the subscriptions to the store state so you don’t have to worry about setting the subscriber on component mount and unsubscribing when the component un-mounts. Where things differ, is you are able to keep the interaction with the store in context with the component using it.

Another advantage to using hooks is that you can compose them into your own custom hooks. You can do the same with higher order components too, but let’s take a look at the difference. Here’s a method of creating a common higher order component to provide to any component that needs a price for a given product.

const { withSelect } =;
const { createHigherOrderComponent } = wp.compose;
const { __ } = wp.i18n;

const withPrice = createHigherOrderComponent(
	withSelect( ( select, { product } ) => {
		return {
			price: select( 'inventory' ).getPrice( ) || __( '...retrieving' ),
	} ),

const ProductWithPrice = ( { product, price } ) => {
	return <div>
		<span className="product-name">{ }</span>
		<span className="product-price">{ price }</span>

export default withPrice( ProductWithPrice );

In the above example, I’ve used the wp.compose.createHigherOrderComponent helper to create a higher order component that can now wrap any component to enhance it with a price state provided by the inventory store. Some caveats though are:

  • The component being enhanced must receive the price prop from withPrice.
  • Components are always wrapped by the higher order withPrice component. Generally this doesn’t matter too much, but it does increase the complexity of the component tree.

So what would things look like if I create a custom hook implementing useSelect?

const { useSelect } =;
const { __ } = wp.i18n;

export const usePrice = ( { product } ) => {
	const { price = __( '...retrieving' ) } = useSelect( ( select ) => {
		return select( 'inventory' ).getPrice( );
	}, [ ] );
	return price;

const ProductWithPrice = ( { product } ) => {
	const price = usePrice( product );
	return <div>
		<span className="product-name">{ }</span>
		<span className="product-price">{ price }</span>

What would you prefer to do? I would prefer the latter, here’s why:

  • usePrice can be used declaratively in any component that receives a product prop.
  • It’s easier to reason about where the price is coming from because it’s reference is directly in context with it’s implementation.

Still, I realize there may be some people that look at this and think:

meh, not much difference really

the astute programmer

Maybe if I start expanding on this example with useDispatch you’ll think differently… so let’s continue!

from withDispatch to useDispatch

The differences between using withDispatch and useDispatch are very similar to the progression we saw in the previous section with components using withSelect vs useSelect. So I’m not going to do the same progression here. Instead, let’s expand on our product price example a bit.

Let’s say the ProductWithPrice component now includes some user interface for seeing what the price would be with a special code they were given on a coupon (I realize this ux is probably not what you’d have in real life, but roll with me for now). So our component now has an input field for adding the code, and a submit button for checking the code. Let’s assume that our inventory store has an action creator for updating the price for a product using a given product name and coupon code. Using withDispatch, and withSelect to create a custom withPrice higher order component you might end up with something like this:

const { withDispatch, withSelect } =;
const { createHigherOrderComponent } = wp.compose;
const { __ } = wp.i18n;

export const withPrice = createHigherOrderComponent(
	withDispatch( ( dispatch, { product } ) => {
		return {
			setCode: ( code ) => dispatch( 'inventory' ).setCode(, code ),
	} ),
	withSelect( ( select, { product } ) => {
		return {
			price: select( 'inventory' ).getPrice( ) || __( '...retrieving' )
	} ),

class ProductWithPrice extends Component {
	constructor( props ) {
		super( props );

	currentCode = '';

	updateCode = ( code ) => {
		this.currentCode = code;

	onClick = () => {
		this.props.setCode( this.currentCode );

	render() {
		return <div>
			<span className="product-name">{ }</span>
			<span className="product-price">{ this.props.price }</span>
			<input type="text" onChange={ this.updateCode } />
			<button onClick={ this.onClick }>{ __( 'Submit Code' ) }</button>

export default withPrice( ProductWithPrice );

Now compare the above with an implementation of useSelect and useDispatch:

const { useSelect, useDispatch } =;
const { useRef, useCallback } = wp.element;
const { __ } = wp.i18n;

export const usePrice = ( { product } ) => {
	const { price = __( '...retrieving' ) } = useSelect( ( select ) => {
		return select( 'inventory' ).getPrice( );
	}, [ ] );
	const { setCode } = useDispatch( 'inventory' );
	const currentCode = useRef( '' );
	const onCodeChange = useCallback( ( code ) => {
		currentCode.current = code;
	} );
	const updatePriceUsingCode = useCallback( () => {
		setCode(, currentCode.current );
	}, [ ] );
	return { price, onCodeChange, updatePriceUsingCode };

const ProductWithPrice = ( { product } ) => {
	const { 
	} = usePrice( product );
	return <div>
		<span className="product-name">{ }</span>
		<span className="product-price">{ price }</span>
		<input type="text" onChange={ onCodeChange } />
		<button onClick={ updatePriceUsingCode }>{ __( 'Submit Code' ) }</button>

Granted, this example is likely something that wouldn’t be implemented quite as it is here in the real world. But it does demonstrate how the more declarative approach of hooks allows for a straightforward read of the logic.

I hope this little overview of two fantastic hooks and where to use them helped you out!

Testing Javascript for your Gutenberg Integrated Plugin

(Edit October 10, 2018) Note: This article is now out of date but is kept published for reference purposes. Nearly everything in Gutenberg is published as a package so for the purpose of testing you can include those packages as a devDependency in your package.json file and jest will know to reference those in tests. 

As a part of my work with Event Espresso I’ve been assisting them with moving over to a more modern Javascript build system.  This has been prompted by the upcoming new editor for WordPress codenamed Gutenberg.  I’m not going to spend a whole lot of time talking about Gutenberg since there’s already a ton of information on the internet.  What I want to do in this post is outline a way for plugin developers to test their custom components/blocks built for Gutenberg using the Jest framework.

Writing javascript tests using Jest is pretty straightforward and this isn’t a how-to-post since there’s a lot of that already available (including this readme the Gutenberg team prepared).  Instead I thought it’d be useful to write how I solved a problem with a particular set of tests I was trying to write for some code I had written (especially since I couldn’t find anything useful on the internet myself to help with it).

The Problem

For Event Espresso I’m creating a reusable react component that exposes a Event Selector populated with events currently on the user’s site.  This will end up getting used in various parts of the Gutenberg friendly api we’re building.  I wanted a way to test this component using jest but ran into a few problems:

  1. The EventSelect component is composed of the Placeholder, SelectControl, and Spinner components from @wordpress/components (or  wp.elements ).
  2. There’s a few other dependencies in file for this component including @wordpress/i18n and @wordpress/data
  3. Gutenberg itself is a plugin and most of the dependencies the code has on Gutenberg itself are thus not available in the context of the javascript being tested (because of assumption of Gutenberg functionality being exposed on the wp global at runtime).
  4. I want to at a minimum use jest’s snapshot feature (using shallow) to verify that EventSelect is rendered correctly depending on the various props provided to it. 

While I could mock all of the dependencies, mocking the WordPress components being used would mean needing to make the assumption they would never change.

The Solution

I’ll get into the specifics of how I fixed this first, and then I’ll take some time to explain why it works (or in some cases why I think it works because frankly I’m still learning Jest and its intricacies).

The very first thing that needs done is importing gutenberg as a package.  Wait what?  Gutenberg is an npm package?  It’s not published to npm, however technically, anything with a npm package.json file in it is already a package.  If it’s hosted on github, you can install it.  So the first step to exposing gutenberg javascript for our tests is to install it!  How do you do that?

npm install WordPress/gutenberg#master --save-dev

That’s it!  In case you’re wondering, npm automatically looks on github for packages if they aren’t in the npm package repository.  So the format I used corresponds to the github {organization}/{repo}#{branch} format.

Next there’s some configuration file changes needed.

The jest.config.json file ended up with this.

	"rootDir": "../../../",
	"collectCoverageFrom": [
	"moduleDirectories": ["node_modules"],
	"moduleNameMapper": {
		"@eventespresso\\/(eejs)": "assets/src/$1",
		"@wordpress\\/(blocks|components|date|editor|element|data|utils|edit-post|viewport|plugins|core-data)": "<rootDir>/node_modules/gutenberg/$1",
		"tinymce": "<rootDir>/tests/javascript-config/unit/mocks/tinymce",
		"@wordpress/i18n": "<rootDir>/tests/javascript-config/unit/mocks/i18n"
	"setupFiles": [
	"preset": "@wordpress/jest-preset-default",
	"testPathIgnorePatterns": [
	"transformIgnorePatterns": [

Three particular  properties you should take note of are:


The property allows you to map module names to a specific location or to a mock.  In this case I wanted to map all @wordpress/* packages to the gutenberg package I just installed.  So this line does exactly that:

"@wordpress\\/(blocks|components|date|editor|element|data|utils|edit-post|viewport|plugins|core-data)": "<rootDir>/node_modules/gutenberg/$1",

Wait a minute!  How can you be using things like@wordpress/data for your imports if that isn’t a package?

Most Gutenberg tutorials you see on the internet give instructions for using the wp global as an external in your js source files, resulting in something like this:

const { Placeholder } = wp.components;
const { withSelect } =;

This works just fine,  however, if Gutenberg ever publishes some of these things as a bona-fide package, and you want to use that package, you’d have to go through and change every file in your source to to imports. I’m lazy, I don’t want to have to go through all my files if that happens. So instead I want to do this:

import { Placeholder } from '@wordpress/components';
import { withSelect } from '@wordpress/data';

However, if I do that, Webpack won’t know what to do with those imports because @wordpress/components and @wordpress/data don’t exist in node_modules.  So we need to help webpack out.  In the webpack configuration file I have something like this:

const externals = {
	'@wordpress/data': {
		this: [ 'wp', 'data' ],
	'@wordpress/components': {
		this: [ 'wp', 'components' ],

The externals object is then assigned to the externals configuration property for webpack.  What this does is alias@wordpress/data to the global.  So on builds any imports are correctly translated to use the global.

However, when running jest tests, jest does not work with the webpack builds (obviously) and is oblivious to this aliasing.  So when it encounters the imports (and goes to translate them to commonjs modules) it can’t find the @wordpress/* packages.  We get around that by using the moduleNameMapper property.

You’ll also notice that I mapped tinymce to a specific location for a mock.   What I discovered is that jest will follow the package import chain all the way down.  I would hit import not found for tinymce because guess what?  Gutenberg itself sets up tinymce as an external in its webpack config.  Since I’ll never need tinymce for my own testing (and shouldn’t need it anyways), I can just mock it.  So this line ends up being:

"tinymce": "<rootDir>/tests/javascript-config/unit/mocks/tinymce",

The path it points to simply contains this the tinymce.js file I created with this as its contents:

module.exports = jest.fn()

Which is just a handy method jest provides for mocking.

Finally, you’ll see that I also mock @wordpress/i18n.  The interesting thing here is that because @wordpress/i18n exists as a package.  I didn’t have to mock it.  However, I don’t really need to initialize jed or anything with i18n so to avoid errors related to it not being initialized in the test environment (and the usage of an actual text_domain in any i18n function calls), its better to just mock it.  So this line…

"@wordpress/i18n": "<rootDir>/tests/javascript-config/unit/mocks/i18n"

…points to the i18n.js file which currently has this as its contents:

module.exports = {
	 __ : (string) => {
		return string;

Right now I’m only mocking the __ function, but as I start testing various code that utilizes other wp.i18n functions I’ll add them to this as well.

The next property I want to zero in on in the jest.config.json file is the setupFiles property.  This property is used to indicate any files you want executed before jest runs tests.  In particular, take note of this file reference:


This points to a setup-globals.js file at that path and its contents are this:

 * Setup globals used in various tests
// Setup eejsdata global. This is something set in EE core via
// wp_localize_script so its outside of the build process.
global.eejsdata = {
	data: {
		testData: true

// Set up `wp.*` aliases.  Doing this because any tests importing wp stuff will
// likely run into this.
global.wp = {
	shortcode: {
		next() {},
		regexp: jest.fn().mockReturnValue( new RegExp() ),

].forEach( entryPointName => {
	Object.defineProperty( global.wp, entryPointName, {
		get: () => require( 'gutenberg/' + entryPointName ),
	} );
} );

This is needed not because I’m going to be using the wp global anywhere in the source js I’m testing, but because I’m actually importing Gutenberg source for the tests, some of the Gutenberg files ARE referencing the wp globals and thus they need to be defined to avoid undefined errors when running tests.  With this bit of code, we’re linking up the wp.{module name} with its module location in the node_modules folder.  So for instance anytime jest encounters wp.blocks it will set the property to the module loaded from node_modules/gutenberg/blocks.  

The final property I want to zero in on for the jest.config.json file is the transformIgnorePatterns property.  For a while I was struggling with the following error every time I ran a test (prior to this property value being inserted):

huh? what do you mean unexpected token import!

Jest expects packages that are included to be pre-compiled (i.e from ES6 to commonjs).  So if you have any imports that point to uncompiled packages you’ll get the above kind of error.  Since we’re including gutenberg as a package straight from its repo, we don’t have the compiled assets, hence the need to let jest know it needs to transform any imports it comes across in gutenberg. I accidentally discovered this when I was reading through the Jest documentation and came across this line:

Since all files inside node_modules are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors.

Jest Documentation for transformIgnorePatterns

Oooooo, ya I’m getting syntax errors.  What I didn’t realize is that this property allows you to whitelist things you want to be transformed. Groovy, so as a reminder here’s what I ended up using:

"transformIgnorePatterns": [

This then made sure that anytime the node_modules/gutenberg package (or any dependencies in those packages) were imported, the code referenced would be transformed into something jest can work with.  Say good bye to syntax errors!

Winner winner, chicken dinner!

With all that work, the code I wanted tested:

 * External dependencies
import { stringify } from 'querystringify';
import moment from 'moment';
import { isUndefined, pickBy, isEmpty } from 'lodash';
import PropTypes from 'prop-types';

 * WP dependencies
import { Placeholder, SelectControl, Spinner } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { withSelect } from '@wordpress/data';

 * Internal dependencies
import { buildEventOptions } from './build-event-options';

const nowDateAndTime = moment();

export const EventSelect = ( {
} ) => {
	if ( isLoading || isEmpty( events ) ) {
		return <Placeholder key="placeholder"
			label={ __( 'EventSelect', 'event_espresso' ) }
			{ isLoading ?
				<Spinner /> :
					'There are no events to select from. You need to create an event first.',

	return <SelectControl
		label={ selectLabel }
		value={ selectedEventId }
		options={ buildEventOptions( events ) }
		onChange={ ( value ) => onEventSelect( value ) }

 * @todo some of these proptypes are likely reusable in various place so we may
 * want to consider extracting them into a separate file/object that can be
 * included as needed.
 * @type {{events: *, onEventSelect, selectLabel: *, selectedEventId: *,
 *   isLoading: *, attributes: {limit: *, orderBy: *, order: *, showExpired: *,
 *   categorySlug: *, month: *}}}
EventSelect.propTypes = {
	events: PropTypes.arrayOf( PropTypes.shape( {
		EVT_name: PropTypes.string.required,
		EVT_ID: PropTypes.number.required,
	} ) ),
	onEventSelect: PropTypes.func,
	selectLabel: PropTypes.string,
	selectedEventId: PropTypes.number,
	isLoading: PropTypes.bool,
	attributes: PropTypes.shape( {
		limit: PropTypes.number,
		orderBy: PropTypes.oneOf( [
		] ),
		order: PropTypes.oneOf( [ 'asc', 'desc' ] ),
		showExpired: PropTypes.bool,
		categorySlug: PropTypes.string,
		month: PropTypes.month,
	} ),

EventSelect.defaultProps = {
	attributes: {
		limit: 20,
		orderBy: 'start_date',
		order: 'desc',
		showExpired: false,
	selectLabel: __( 'Select Event', 'event_espresso' ),
	isLoading: true,
	events: [],

 * Used to map an orderBy string to the actual value used in a REST query from
 * the context of an event.
 * @todo this should be moved to a mapper library for various EE Rest Related
 * things maybe?
 * @param {string} orderBy
 * @return { string } Returns an actual orderBy string for the REST query for
 * 					  the provided alias
const mapOrderBy = ( orderBy ) => {
	const orderByMap = {
		start_date: 'Datetime.DTT_EVT_start',
		end_date: 'Datetime.DTT_EVT_end',
		ticket_start: 'Datetime.Ticket.TKT_start_date',
		ticket_end: 'Datetime.Ticket.TKT_end_date',
	return isUndefined( orderByMap[ orderBy ] ) ? orderBy : orderByMap[ orderBy ];

const whereConditions = ( { showExpired, categorySlug, month } ) => {
	const where = [];
	const GREATER_AND_EQUAL = encodeURIComponent( '>=' );
	const LESS_AND_EQUAL = encodeURIComponent( '<=' );

	if ( ! showExpired ) {
		where.push( 'where[Datetime.DTT_EVT_end**expired][]=>&where[Datetime.DTT_EVT_end**expired][]=' +
			nowDateAndTime.local().format() );
	if ( categorySlug ) {
		where.push( 'where[Term_Relationship.Term_Taxonomy.Term.slug]=' + categorySlug );
	if ( month && month !== 'none' ) {
		where.push( 'where[Datetime.DTT_EVT_start][]=' + GREATER_AND_EQUAL + '&where[Datetime.DTT_EVT_start][]=' +
			moment().month( month ).startOf( 'month' ).local().format() );
		where.push( 'where[Datetime.DTT_EVT_end][]=' + LESS_AND_EQUAL + '&where[Datetime.DTT_EVT_end][]=' +
			moment().month( month ).endOf( 'month' ).local().format() );
	return where.join( '&' );

export default withSelect( ( select, ownProps ) => {
	const { limit, order, orderBy } = ownProps.attributes;
	const where = whereConditions( ownProps.attributes );
	const { getEvents, isRequestingEvents } = select( 'eventespresso/lists' );
	const queryArgs = {
		order_by: mapOrderBy( orderBy ),
	let queryString = stringify( pickBy( queryArgs,
		value => ! isUndefined( value ),
	) );

	if ( where ) {
		queryString += '&' + where;
	return {
		events: getEvents( queryString ),
		isLoading: isRequestingEvents( queryString ),
} )( EventSelect );

And the actual test I tried to get working:

import { shallow } from 'enzyme';
import { EventSelect } from '../index';

describe( 'EventSelect', () => {
	it( 'should render', () => {
		const wrapper = shallow( <EventSelect /> );
		expect( wrapper ).toMatchSnapshot();
	} );
} );

results in a winner!

whoah, there’s that green I’m looking for!

I’m not done yet, but the big part is done, now I can go ahead and write tests for various states of the component.

Any thoughts?  I’m pretty new to jest so there may be some things I’m not doing “right”.  If you’re a javascript/jest guru and have some pointers to help improve on this I’m all ears 🙂

If you want to follow along with my journey in writing this component and the related tests etc, you can go to this pull request.

Something every Language/Library debate needs to keep in mind….

There’s some discussion happening right now in the WordPress world about what javascript framework to add to WP core.  These kind of debates happen frequently in the programming world (Google “PHP sucks” for some great examples).  In the course of these types of discussions, support is usually brought up for one point of view or another by pointing to what others have written about it on the internet.  Certainly it is reasonable to glean from what has been written,  but I think it’s also important to recognize there is a silent majority of programmers out there that we’ll never get input from as demonstrated by this simple diagram I did up (horrendous but communicates the point I want to make):


The intersection of people who write (and you might add write well to that) and those who program (and you might add those who program well to that) is a small portion of the entire picture.  Sure, we don’t discard what is written about, but let’s not give it undue weight either.  Ultimately, there is a silent majority of people building solutions who really don’t care about these discussions or flame wars because they are using what gets the job done.

At the end of the day, use what gets the job done.  Learn it well.  Learn it deeply.  If you’re one of the few who also has the gift/time to write, write about it!

On Vision

This is a post that has been percolating as a draft post for nearly two or three months now.  But as a theme, its something I’ve wrestled with far longer.  Those who know me well, know that at my core, I’m kind of a systems and strategy kind of guy. What makes gets my ticker picking up its pace,  is when I get to work with a big picture idea and help generate/coach the strategies and systems to see that that big picture come alive and grow.  And so, that’s why this post reflects something that strums the passion bone in my body.

I want to spend a little bit of time articulating some things I’ve come to believe about a word that gets used a lot,  but is rarely understood fully.   This post is sparked in part because I think there’s a lot of misunderstanding about what vision is, and what it is not.  Part of that is because its so elusive, and part of it is because it frequently rides the buzzword wave.  So here’s what I think about vision:

Vision inspires curiosity.

You know you’ve heard, read, or experienced vision when it leaves you hanging,  when it sparks that desire in you to know more.  That’s why some of the most compelling visions are those that paint a picture, or connect a story, with a future.

Vision does not answer all the questions.  It doesn’t tell you how something is going to happen.  It doesn’t tell you when something is going to happen.  It sometimes doesn’t even articulate where.  But compelling vision will always leave you with questions.

In the end, vision begs strategy because it inspires curiosity.

Vision Polarizes.

This is crucial.  A vision that everyone likes, is not vision, its a sedative.  The reality is, visionaries (you know, those people with a vision), have a lot of enemies.  They get a lot of flak and its often only in hindsight through the eyes of history, when they start to get labelled visionaries, that the animosity tapers down a bit.  The reality is, really compelling visions have haters and lovers.  A compelling vision is something that either calls people to it, or repels them.

It polarizes.

Coincidentally, that’s why vision is so powerful.  While a vision is polarizing, its also uniting. How?  People who are captivated by the vision, who buy into it share a common cause – a cause worth fighting for.  Sedatives, don’t inspire that kind of passion, or unity.

This also means that its really difficult for a committee to come up with a vision.  Committees are great for hashing out ideas, for brainstorming, for strategizing, for planning, coming up with mission statements, x year plans, etc..  But not for creating vision.  If a vision is launched by a committee I can pretty much guarantee you it will be safe, not polarizing and ultimately, not really a vision. Maybe what they’ll have is a really great mission statement, or slogan, or even a plan – but not a vision.

Incidentally, this also means, that great visions aren’t always popular, and not so great visions sometimes are.

Vision is an “impossible” future.

More than just a picture of something different than the status quo, on the surface, visions seem impossible.  That’s because visions paint a picture of something that isn’t in the midst of what is.  Anything else isn’t a vision it’s just a report.

This is also why having a vision is not the same thing as having a goal.  With vision, you don’t even know if it will come to pass.  You dream for it, you desire it, you’re passionate for it (if you’ve caught it), you even pursue it,  but at times it seems so impossible that you’re not sure you’ll ever see it happen.

Sometimes you don’t.

A goal on the the other hand is something you expect to reach.  It has an obtainable finish line.  Difficult maybe, and certainly something you may not complete.  But nevertheless can happen.  It’s possible.  Visions aren’t really like that.

This is one of the reasons why visions are so polarizing because some people will hear a vision and laugh at the audacity of those who believe in that vision.  “Such an impossible goal!”, they say.  Except, its not a goal.

A goal is deciding that you are going to quit smoking.  A vision is seeing the entire world free of the addiction of tobacco.

A goal is to build a rocket to reach orbit.  A vision is to land a man on mars.

A goal is to build an electric car.  A vision is to end humanities dependence on oil.

Catch the drift?  Oh and here’s another little interesting thing.  Visions are realized by goals. Lots and lots of incremental, obtainable, strategical, itty bitty, goals. The impossible reached by a long chain of possibles.  But it all starts with a dream for something outrageous.

This is why…

Vision requires sacrifice.

To get from here to there is going to take a lot more than wishful thinking.  If a vision is a picture of something impossible, then it its not a skip, hop, and dilly dally dance away.  It’s hard work, and perseverance, and endurance and sweat and tears, and loss, and pain to get there.  Sounds like fun doesn’t it?

The interesting thing is, compelling vision has increased value because of the cost to achieve it.  But conversely, without any cost, does the end really matter?

That’s why its interesting to watch what happens with people who are captivated by a vision.  No amount of sacrifice seems too much to inch closer to realizing that impossible reality.

Vision doesn’t always generate a movement.  But it always starts with one person.

The funny thing about vision, is that it sometimes can be so polarizing that the only person who believes it, is the one in who it was birthed.  Vision can live and die in the life of one individual.  Sad, but true (and sometimes good).

But the underlying truth, is that regardless of whether vision results in a movement or not, it is always birthed in the heart and soul of a single person.  Call it muse, or God given, or calling, or inspiration – but that spark is awakened in some guy or some gal and lives when they can’t shake it, and then embrace it.

Yet another equal and perhaps even more powerful truth, is that while a vision starts with one person, it never gets completed with just one.  That’s why I’ve found that a vision often lives and dies on how well it gets communicated, and I guess in the end, how polarizing (and thus compelling) it really is.

Vision isn’t taught, it’s caught.

You can’t teach people vision.  You invite them.  You can’t reason vision with people. After all, it’s impossible right? No, reasoning doesn’t work.  You inspire, you challenge…

You lead.

Visionaries, don’t get people on their vision train by fancy billboards, and great marketing campaigns (it only seems like they do).  Great visionaries have a vision that captivates people because they are living it, they are leading it.  An impossible reality, that’s already real to them.

Vision is not complicated.

Ha! Once the planners and the strategy masters, and engineers start mapping out the goals to see that impossible vision become reality, it certainly starts to seem complicated. But the vision itself, the essence of what gets dreamed about and communicated, and shared, isn’t complicated.

It may be impossible, but it’s simple. If you can’t remember a vision, then it’s complicated, and not really a vision (probably more a plan).

But let’s not confuse a slogan with a vision. Slogans are birthed from visions, but a vision never comes from a slogan. When you hear the well known slogan “I have a dream”, you immediately connect it with the vision Martin Luther King Jr. had for a better world.

Without the vision, “I have a dream” is just an incomplete sentence.

What’s your vision?

Here’s another somewhat uncomfortable truth.  Some of us will never have vision sparked, or birthed in us (and unfortunately some people uncomfortable with that try to manufacture it).  The reality is, that’s okay.  I believe that some of us were never meant to birth the vision…

But all of us are meant to carry a vision.

In the end…

These are just a few thoughts and observations I’ve had/made about vision.  As time goes on there likely will be more I could add (and may add) to this post.  But for now, just wanted to get this written out.  What do you think about vision?  What would you add to this?



Using for automated WordPress plugin testing.

A few months ago, one of the teams I work with went on the hunt for a good continuous integration service for running tests on the code we write.  We jumped on the unit test bandwagon at the beginning of the year and wanted to really amp up the quality of our product by having tests run on every commit.  I was tasked with this job (and anyone who knows me knows I LOVE playing with new things, so it was a task I was looking forward to doing)

Most WordPress users are familiar with and the internets were full of instructions for getting things plugged in and up with travis.  Unfortunately, our project is inside a private github repo so we couldn’t use the free travis plan to run our tests on and the premium plan was a bit to pricey for our first attempt at this.  So after searching around, I stumbled on circle.  From all appearances, circle looked like it would work very similarly to travis and bonus points were that their plans are much cheaper – so great for getting started with.

All their documentation was great for getting things hooked up to your github repo, and getting started with tests, with the exception of one glaring thing.  I couldn’t find ANYTHING on the internets about how to setup a circleci.yml file for automating WordPress and WordPress plugin tests. Boo.  But actually, probably better in the long run because I ended up having to come up with something through trial and error and in the process learned a lot about the magic behind these scripts.

In this post, I’m not going to highlight how to setup unit testing for your WordPress plugin since there’s already a wealth of knowledge on the internets for that. Instead I just want to give an example circle.yml file that we use for our plugins at

So in the interest of passing on what I learned for anyone else searching the internets, I present to you our circle.yml script:

## Customize the test machine

    America/Denver # Set the timezone

  # Version of php to use
    version: 5.4.21

  # Add some environment variables
    CIRCLE_ENV: test
    WP_CORE_DIR: /home/ubuntu/wordpress-develop
    WP_TESTS_DIR: /home/ubuntu/wordpress-develop/tests/phpunit
    plugin_loc: /home/ubuntu/$CIRCLE_PROJECT_REPONAME
    plugin_dir: /home/ubuntu/wordpress-develop/src/wp-content/plugins/$plugin_slug
    plugin_tests_dir: /home/ubuntu/wordpress-develop/src/wp-content/plugins/$plugin_slug/tests

## Customize dependencies
    #enable xdebug.  LINE 1/2 to uncomment if you want to run a code coverage report.
    # - sed -i 's/^;//' ~/.phpenv/versions/$(phpenv global)/etc/conf.d/xdebug.ini
    #setup WP install
    - git clone git:// $WP_CORE_DIR;
    - cd $WP_CORE_DIR && cp wp-tests-config-sample.php wp-tests-config.php && sed -i "s/youremptytestdbnamehere/wordpress_test/" wp-tests-config.php && sed -i "s/yourusernamehere/root/" wp-tests-config.php && sed -i "s/yourpasswordhere//" wp-tests-config.php;
    # move plugin into tests/src
    - mv $plugin_loc $plugin_dir;
    # set up database
    - mysql -e 'CREATE DATABASE wordpress_test;' -uroot;
    # setup phpunit
    - wget && chmod +x phpunit.phar && mv phpunit.phar /home/ubuntu/.phpenv/shims/phpunit

## tests override
    # comment out the below line to run a code coverage report.
    - cd $plugin_tests_dir; phpunit
    ## LINE 2/2 to uncomment if you want to run a code coverage report.
    # - cd $plugin_tests_dir; phpunit --coverage-html $CIRCLE_ARTIFACTS

Where does the script go?

The circle.yml should be in the root directory of your WordPress plugin, and I’m assuming that the plugin itself has all its tests in a /tests/ directory off of the root.

What does all that stuff mean?

The circle.yml script itself is based off of the sample file circle provides. I just had to use trial and error to figure out setting up all the components needing setup on the virtual machines circle spins up to run the tests on. Let’s walk through the sections one by one.

The machine section basically is the group for all the machine variables controlling the vm setup.

In this section you can set what the timezone will be setup for the spun up machine. In reality, you don’t have to put anything here, because WordPress runs in UTC. But if you are doing anything else on your machine or are collecting errors etc., setting the timezone could be useful.

Here you set what php version you want the tests to run in. One thing I haven’t been able to figure out on circle yet is whether I can have our tests run consecutively on different php versions (which seems to be REALLY easy with travis). Note, PHP5.2 is NOT an option with circle (which may be an option with travis, not clear on it).Since most hosts dropping support for PHP are jumping right to PHP5.4 (and skipping PHP5.3) that’s the version we’ve decided to run our automated tests on.

In this section you set all the environment variables you want exposed in bash for your test setup. Note the following variables I’ve setup:

  • CIRCLE_ENV: test – currently unused, I just used this to set that we’re in the CIRCLE_ENV testing environment. At some point I may use this in our test scripts so I have a way of knowing we’re running tests on a circle server.
  • WP_MULTISITE: 0 – used by WordPress test library, this basically allows us to designate that we are not running our tests on WordPress multisite (of course when we DO want that to happen we change this).
  • WP_CORE_DIR – here we set the path where wp core tests suite will be installed. Note that circle vm’s are spun up with a user named ubuntu. So all files are typically found in the ubuntu user directory.
  • WP_TESTS_DIR – here we set the path for where the tests directory will be for the WordPress phpunit tests.
  • plugin_loc – here is the path set for where the plugin will be installed. Note I use a special environment variable Circle automatically exposes called $CIRCLE_PROJECT_REPONAME. Circle automatically pulls in the project from the repo its connected with and installs it in a path in the home directory. I set this as a variable so later I can instruct the script to move the project from that location to its new home in the WordPress wp-content/plugins folder.
  • plugin_slug – just to save typing and be more explicit – this is an alias for $CIRCLE_PROJECT_REPONAME
  • plugin_dir – this is the path where the plugin will be moved to after WordPress is installed.
  • plugin_tests_dir – this is the path to the tests folder where phpunit will be run for our plugin.

This section of the circle.yml file is where you can setup all the dependencies before the tests are run. In our file, we only use the “pre” index (but there are others you can read about in the circle docs).

This is where you list instructions for how circle should setup the machine before the tests are run. It appears that any bash commands can be included as separate line items in this list.

  • sed -i 's/^;//' ~/.phpenv/versions/$(phpenv global)/etc/conf.d/xdebug.ini – note this line is commented out by default. it basically takes care of enabling xdebug for php. If you want to do a coverage report at the end of your tests then you need to remove the commenting.
  • git clone git:// $WP_CORE_DIR; – here we’re pulling in the WordPress development repo that contains all the WordPress tests.
  • cd $WP_CORE_DIR && cp wp-tests-config-sample.php wp-tests-config.php && sed -i "s/youremptytestdbnamehere/wordpress_test/" wp-tests-config.php && sed -i "s/yourusernamehere/root/" wp-tests-config.php && sed -i "s/ – here is where we give instructions to cd into the WordPress installation we just installed, and then modify the wp-tests-config.php file to have the db instructions.
  • mv $plugin_loc $plugin_dir; – we’re moving the plugin the tests are being run against from the directory it was installed in, into the WordPress plugins folder where it needs to be.
  • mysql -e 'CREATE DATABASE wordpress_test;' -uroot; – This just sets up the db to be used by the tests suite.
  • wget && chmod +x phpunit.phar && mv phpunit.phar /home/ubuntu/.phpenv/shims/phpunit – for some reason, the installation of phpunit that comes with circle machine installations is just not setup correctly because it doesn’t work. So this line takes care of installing the latest phpunit so that it does work. This little line is the culmination of hours of work (just because there’s so little usable information, I’m not a server guru, and I had a lot of trial and error).

In this section of the circle.yml file you are able to give specific instructions regarding the tests. The only parameter we use in our file is the “override” one. This just ensures that the default circle test isn’t run but instead what we specify.


  • cd $plugin_tests_dir; phpunit – here we cd into the tests directory for our plugin and run phpunit. That’s it! Now if you want to run a code coverage report then you make sure this line is commented out and uncomment the following line…
  • cd $plugin_tests_dir; phpunit --coverage-html $CIRCLE_ARTIFACTS – this line is commented out by default. However, if you wish to run a code coverage report then xdebug has to be enabled, and then you remove the comments from this line and comment out the previous line. What happens is when the test is complete, phpunit will create a html code coverage report and install it in the $CIRCLE_ARTIFACTS path. The groovy thing about this is that when complete, the circle artifacts path is visible on the internet so you can click the provided link (or share it with the team) to access the code coverage report. The reason why this is commented out by default is it takes significantly longer to generate a report than just running the tests, so we don’t want a report generated on every commit.


That’s it! I hope this is useful for anyone wanting to get WordPress unit testing setup on the excellent (cheaper) circle service. If any of you reading this are more of a server guru than I am and have suggestions for improvement I welcome that in the comments!

If I was in charge of a telecommunications company…

Yes, this is one of those “If I was in charge, I’d do this…” posts.  Don’t we all have opinions on how companies should be run?  Just had these thoughts today so decided to write them down.  Canada is known as one of the worst places for mobile phone plans (from a consumer perspective), largely because of the lack of competition.  If by some freak cosmological accident I ended up in charge of a telecommunications company, here’s some things I’d do:

I’m not going to talk about pricing or packages or anything like that, because at the end of the day what matters most for company longevity is customer loyalty and word of mouth marketing (even more so in today’s hyper social world).  The only reasons why I think the existing companies are doing so well in Canada now are because of their entrenched position with infrastructure, and the lack of choice for consumers.  With that said,

1. I’d ensure that our company has some sort of automated process that scans existing customers accounts (ooo privacy, but bear with me) and if there are any current company promotions that are better plans (either in terms of the same as what they have but cheaper, or more features than what they have for same price) than what the customer currently has we automatically switch them to the cheaper plan and notify them.

2. The plans would be simplified (which would need to happen for number 1 to work effectively).

3. Company wide policy that if a customer calls and complains about something not working, and they have ANY difficulty getting the level of service they asked for, we immediately grant them at least a free month’s service.

4. For customers who have been with the company for over three years.  We surprise a certain number of them randomly once a year with free phones and/or upgraded plans for their current phones.

That’s just four things.  Not a lot, and I fully realize there’s a lot more involved with running a company, but four things that I think would help towards gaining long term customers and viral word of mouth marketing.

What would you add?

FireHost and WordPress Multi-site… how well do they play together?

Recently, one of my clients purchased a server with  We’d been on the search for a new web host for some time now to serve as the infrastructure supporting upcoming web applications we have in the works.  We needed a company who is well recommended, and will help us scale and scale quickly.

You pay a more for a host like this  but it’s part of the investment costs you need to make if you want to be positioned well for solid growth as a business.

Anyways, the purpose of this post is NOT to discredit or gripe about yet another hosting company that fails to live up to expectations. We actually really like the setup we have at FireHost. Although getting things setup were a bit of a pain – their support has been very prompt and generally okay.  No, this post is more of a fyi for folks who are in a similar situation as us.  I couldn’t find any information on this subject on the nets so thought I’d post my own findings.

One of the major components of some projects we are working on this year involves the use of WordPress multisite.  It will provide the backbone of what we are building and is crucial that we have a server environment that supports this.  FireHost does except for one niggling problem.  They have a super awesome “Web Application Protection” firewall that works really well, too well, and prevents normal usage of WordPress multisite.

At issue is that any subsites created on WordPress multisite will fully function as long as those subsites don’t post any images or certain html in their posts.  Cause if they do,  BAM, the firewall sees that as a xss attack and shuts her down.

That’s no good is it?  No.  But wait, FireHost has the solution.  All you have to do, is whenever this happens you just send them the path for the sites that the firewall does its thing on and they’ll add an exception.  Greeatt!  Except that we’re planning on using WordPress multisite to well actually make it easy for people to signup and get started on a new site right away (you know kind of like how people expect things to work? right?).  So yeah, major pain to have to send a block of paths every time the firewall acts up.

I’m not going to tell you the solution we worked out but let’s just say not ideal.

Silly?  Yeah.  I get it. But obviously someone at FireHost needs to do some thinking about how this firewall is setup and put something in place to allow for easier management of WordPress multisite while keeping the firewall working on things that it should work on, or at least be clear about the side affect of the WAP for those using WP multisite, would have saved a lot of back and forth with tech staff.  At the very least, create some sort of API or secure service for automating the firewall exceptions in cases like this where sites are being created dynamically via an application like WordPress multisite.

Anyways, again we do like what we have so far with FireHost except for this firewall experience, but I just wanted to post this up in case anyone else is thinking of using multi-site with FireHost and wondering why its not working as expected.

(I also have another reason for posting…secretly hoping some server guru out there will be able to explain how I’m either an idiot for expecting the firewall to be set up so multi-site works, or how FireHost can do things so multisite will work fine).

Update: December 2014

Just posting an update for anyone who visits this post via search engines (there are a few of you its seems.  Besides the fact that Firehost did contact us within the 30 day window that was put forward by their CEO/founder in the comments to this post, we never did get on any “beta” program.  The solution they are proposing for clients needing their own managed WAF is a $1500+/mo cost solution, which is not startup friendly.  They did offer to help get us up on ModSecurity as an alternative to their WAF solution but in the end my client and I just decided to fire Firehost (yeah pun intended) as our hosting provider and we joined the cool cats over at Digital Ocean.  We figured if we’re going to be doing most of the server setup/managing ourselves then no sense in paying a “managed” hosting provider to do it for us.  We’ve been on Digital Ocean for about 5 months now and absolutely LOVE it.

WP 3.7 drops with an interesting surprise…

I thought I was following the development of WordPress 3.7 fairly closely but something totally missed my notice and only caught my attention when a plugin I develop stopped working with the latest version of WordPress.

The culprit?

do_action( 'save_post', $post_ID, $post, $update );

Notice anything different?  The difference is that this hook used to only have 2 parameters, “$post_ID”, and “$post” but NOW it has a third one, “$update”.  It’s actually a nice addition as it makes it super easy to determine whether the post is being updated or not.  However, due to the way I hooked into this action (with a function that had extra parameters on it), Organize Series broke.  Easy enough fix, but quirky enough that I thought it deserved a post as I haven’t seen anybody mention this little addition!


Get wp-cli running with MAMP

I got really intrigued with the wp-cli tool for command line WordPress (seriously awesome, check it out)… however I haven’t switched my osx machine to use the built in php and mysql so I kept getting this error:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

Easy fix:

sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock

And BOOM! I’ve got wp-cli working now.