WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a command line script for maintaining a wordpress plugin and have to load the wordpress core to be able to access wordpress functions.

This problem is very similar to Initialize WordPress environment to use in a real cron script. Though it differs from it as the referred question is supposed for use with a (real) cron script which can be accomplished otherwise then by starting a command line php script. As the referred question is already answered and this answer is not satisfying my needs I started this question.

So what it is necessary in a command line script to initialize the wordpress environment?


share|improve this question
up vote 14 down vote accepted

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

    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');


share|improve this answer
Just to add to this, you'll want to run ob_end_clean(); at after that as otherwise wordpress captures all your output and doesn't show anything until the very end. – Hosh Sadiq May 30 at 12:45

We also needed to do this in WP-CLI. In order to properly handle all the edge cases, such as incorrect database credentials, we ended up rolling our own version of the wp-settings.php file:


The good news is that you don't have to deal with the messy process of loading WordPress, if you don't want to. 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:

global $wpdb;

echo implode( ' ', $wpdb->tables() ) . "\n";
share|improve this answer
So eval-file makes all WordPress functions available without having to require anything? This answer would be more clear with a quick example of such a PHP script. – Kaelin Colclasure Sep 8 '14 at 16:20
@KaelinColclasure Yep; added example. – scribu Sep 8 '14 at 17:24

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.