Wordpress - Initialize WordPress environment to use in command line script

I came up with following solution. The script have to start with the following code.

<?php
    if( php_sapi_name() !== 'cli' ) {
        die("Meant to be run from command line");
    }

    function find_wordpress_base_path() {
        $dir = dirname(__FILE__);
        do {
            //it is possible to check for other files here
            if( file_exists($dir."/wp-config.php") ) {
                return $dir;
            }
        } while( $dir = realpath("$dir/..") );
        return null;
    }

    define( 'BASE_PATH', find_wordpress_base_path()."/" );
    define('WP_USE_THEMES', false);
    global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
    require(BASE_PATH . 'wp-load.php');

Related

  • How to determine wordpress base path when wordpress core is not loaded
  • https://stackoverflow.com/questions/9101503/include-wordpress-core-into-own-scripts

If you don't want to deal with the messy process of loading WordPress manually, you can just use WP-CLI's eval-file command:

wp eval-file my-script.php

The my-script.php file can contain any WP function call. For example:

<?php
global $wpdb;

echo implode( ' ', $wpdb->tables() ) . "\n";