Initialize WordPress environment to use in command line script

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.

Read More

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

Related

Related posts

Leave a Reply

2 comments

  1. 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

  2. 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";