Execute command line PHP script from within WordPress

You can try to load the wp-load.php of wp-config.php files manually, but then some defines are not set (like HTTP_HOST). An easier way is to use the eval-file method of the wp-cli package. No you can just do:

wp-cli.phar eval-file myfile.php

And in your file, you can call all the usual WordPress methods. Only make sure to explicitly use global for variables, because this is executes from within a function. For example:

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

$id = get_current_blog_id();
die("ID = $id\n");
Tag: | Category: