1

How to Load WordPress Multi-Site in a script

Posted (Updated ) in PHP

A task I’ve been wrestling with lately is to load WPMU in a PHP script which will be accessed regularly via cron using CURL. Getting WPMU to load was simple enough

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
 
$_SERVER['HTTP_HOST'] = 'yourdomain.com';
 
ini_set('display_errors', true);
 
/**
 * BEGIN LOAD WORDPRESS
 */
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()."/" );
global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
require(BASE_PATH . 'wp-load.php');
 
/**
 * END LOAD WORDPRESS
 */

The above takes care of 90% of the work. All that’s left is an annoying bug whereby all get_option() lookups were returning details for the main blog despite being in a switch_to_blog() block. After a bit of debugging it turns out this is due to get_option() caching its values from the main blog and never expiring its cache when switching. There’s a pretty nifty action you can use to fix this:

1
2
3
4
5
6
7
8
function switch_to_blog_cache_clear( $blog_id, $prev_blog_id = 0 ) {
    if ( $blog_id === $prev_blog_id )
        return;
 
	wp_cache_delete( 'notoptions', 'options' );
	wp_cache_delete( 'alloptions', 'options' );
}
add_action( 'switch_blog', 'switch_to_blog_cache_clear', 10, 2 );

There you have it. Below is the script in its entirety for loading WPMU, switching to blog 31 and grabbing its name:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
 
$_SERVER['HTTP_HOST'] = 'yourdomain.com';
 
ini_set('display_errors', true);
 
/**
 * BEGIN LOAD WORDPRESS
 */
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()."/" );
global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
require(BASE_PATH . 'wp-load.php');
 
function switch_to_blog_cache_clear( $blog_id, $prev_blog_id = 0 ) {
	if ( $blog_id === $prev_blog_id )
		return;
 
	wp_cache_delete( 'notoptions', 'options' );
	wp_cache_delete( 'alloptions', 'options' );
}
add_action( 'switch_blog', 'switch_to_blog_cache_clear', 10, 2 );
 
/**
 * END LOAD WORDPRESS
 */
 
switch_to_blog( 31 );
var_dump(get_bloginfo('name'));
restore_current_blog();

For more information see: