← All Articles A Product of Kinsa Creative

Work with WordPress from an External File to be Run from the Command Line

Using the WP CLI

In the HTML root, create a PHP file. It should be at the same directory level as the wp-load.php file.

Run wp eval-file file-name.php to run the script. If using Ddev, run it as ddev wp eval-file file-name.php.

Using the PHP command

In the HTML root, create a PHP file. It should be at the same directory level as the wp-load.php file.

At the top of that file, add:

<?php
define( 'WP_USE_THEMES', false );
require_once( './wp-load.php' );

That is enough to set up the connection to the WordPress database and access the WordPress functions.

From there, a query can be written for example to get all posts of a certain taxonomy that have an ACF field populated:

$posts = new WP_Query( array(
    'posts_per_page' => - 1,  // retrieve all items without regard for pagination rules
    'tax_query'      => array(
        array(
            'taxonomy' => 'my-taxonomy',   // taxonomy name
            'meta_key' => 'my-acf-field-name',  // an ACF field
            "operator" => "EXISTS",
        )
    )
) );

if ( $posts->have_posts() ) {
    while ( $posts->have_posts() ) {
        $posts->the_post();
        // do something with the post 
    }
} else {
    echo "No posts found\n";
}

The file can then be executed by running: $ php my-file-name.php. If working in Ddev, first SSH into the environment: $ ddev ssh and then run the file.

To make the file a bit safer, add the following to only allow execution from the command line:

if (php_sapi_name() != 'cli') {
    echo "This application must be run on the command line.\n";
    exit();
}

PHPUnit Testing

This technique for loading Wordpress can be used to access and unit test a WordPress function defined in a theme's functions.php file.

For more on PHPUnit, the documentation covers many concepts.

Install PHPUnit with composer, in the dev environment run (if using Ddev, run $ ddev ssh to access the dev environment): $ composer require --dev phpunit/phpunit.

Create a tests/ directory at the root of a WordPress theme.

Add a file to it: SpamTest.php

In that file, load WP before running the tests:

<?php

// load WordPress
define( 'WP_USE_THEMES', false );
require_once('wp-load.php');

// PHPUnit
use PHPUnit\Framework\TestCase;

// match the class name of the test to the name of the file
// the file name is SpamTest.php so the class should be named `SpamTest`
final class SpamTest extends TestCase {
    public function testEggs(): void {
        // test
    }
}

Run it from the root of the dev environment (once again, if using Ddev, run $ ddev ssh to access the dev environment): $ phpunit wp-content/themes/<mytheme>/tests/SpamTest.php.

Feedback?

Email us at enquiries@kinsa.cc.