I am trying to automatically install a WordPress distribution in PHP with the following code:
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
When I manually run wp_install() [/wp-admin/includes/upgrade.php], I get this error:
Fatal error: Call to a member function flush_rules() on a non object in /home/username/public_html/wp-admin/includes/upgrade.php on line 85
After looking at the WordPress source code, it appears that $wp_rewrite is trying to call flush_rules() when $wp_rewrite itself doesn’t exist.
Another strange twist is that this is virtually the same code as wordpress-cli-installer. My wp-config.php file is automatically generated and ready.
How come wordpress-cli-installer’s code works but mine does not?
EDIT:
After a lot of trial and error, I found out that my code was not working because it was defined and executed in a function. After I separated the code from the function and executed it, it worked. However, that raises another question. Is it even possible to execute the above code inside of a function? I have tried using the $GLOBALS += get_defined_vars();
hack after the require_once statements, but that doesn’t seem to do anything. In other words:
<?php
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
// ^ This works.
// v This won't work.
function run(){
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
}
run();
?>
How do I use the require_once inside of a function while still being able to access and manage the globals?
That idea is wrong in general. You can make global only required variables (which might change from version to version). But the ‘dirty’ way is