Interactive WordPress PHP CLI access

Ever wanted to just poke around inside a WordPress install? Run some code and immediately see the results without logging to the error log or other common approaches? This sort of tool has been available for many languages including PHP (php -a) for some time. It provides rapid experimentation and exploration of language features and behavior.

But what if we could load WordPress into the interactive shell? It was this type of tool that allowed me (and I'm sure many others) to learn the rails api so quickly. Allowing you to perform basic CRUD operations on your models, test out function calls, and see the results in real time.

It's fairly easy to accomplish this with WordPress. Simply include the following file in your WordPress project, we'll call it cli.php.

<?php
    // assumes this file is placed in ../wp
    define('CLI_WP_ROOT', dirname(__FILE__).'/wp');
    $_SERVER['HTTP_HOST'] = 'http://example.dev/';

    ob_start();
    require_once(CLI_WP_ROOT.'/wp-load.php');
    require_once(ABSPATH.'wp-admin/includes/admin.php');
    ob_end_clean();

Clearly you need to make sure your paths and faux HTTP_HOST match the current project.

Then simply start up an interactive php shell and include cli.php.

$> php -a
Interactive shell

php > include 'cli.php';
php > echo get_bloginfo('title');
Test WordPress Site

At this point you should have access to all of WordPress's function library with complete database access so be careful if you are using this in an environment that has important data.

Now you have an interactive session to experiment and explore the WordPress API in real time.

Jonathan D. Johnson

Loving my wife, my sons, and my work. Building codeship by day and packtracker by night, otherwise you can probably find me outside 🧗🏻‍♂️🏕