Chapter 12. WordPress Multisite Networks

With the release of WordPress version 3.0 came WordPress Multisite. WordPress Multisite was known as WordPress Multiuser (WPMU) prior to version 3.0 because it was a separate open source project. Since WordPress and WPMU shared most of the same code, it made sense to roll it all into one project. Multisite gives WordPress administrators the ability to create their own network with multiple sites. All sites on a Multisite network share the same database and same source files. When Multisite is set up, new tables are created in the database for each new website that is created on the network.

Why Multisite?

If you are running more than one installation of WordPress, especially if they are mostly similar websites, you should consider using Multisite to save your valuable time and/or money. Imagine updating all of your WordPress installs at the same time instead of separately. Some benefits of Multisite includes the following (see Figure 12-1):

  • Sharing a common set of plugins, themes, and custom code across many sites.

  • Managing all of the users on your network in one location.

  • Accessing all of your websites with one super administrator account.

  • Updating core WordPress and installed plugins and themes at one time and in one place instead of via multiple websites.

  • Easily deploying a new website with a few clicks instead of building a new installation from scratch.

  • If you are using a child theme framework for all the sites on your network, you could make updates to all of your themes at the same time utilizing available hooks in the theme framework.

  • Allowing users to set up and manage their own sites on your network. An administrator of one site might have a different role on another.

images/bwaw_1101.png
Figure 12-1. Multisite versus standalone sites

Following are some good examples of when to use WordPress Multisite:

  • You need to run a network of similar websites for which each site administrator manages their own site content. Let’s say you need to build a network of school websites for a school district where each school has its own website with mostly the same features. Each site administrator needs to be able to make branding updates via theme settings and update all of the content. WordPress Multisite, yo!

  • You need one website in multiple languages, run by different people, and you don’t have faith in the WordPress Multilingual Plugin (WPML) plugin. WordPress Multisite, yo!

  • You want to set up hundreds of affiliate websites that you can easily manage and add new features. WordPress Multisite, yo!

Why Not Multisite?

Many of the reasons to use Multisite are also reasons to avoid it. For some projects, managing all users on the same network will cause confusion or even legal issues. For some projects, you may need to run different versions of certain themes, plugins, or WordPress itself.

Third-party plugins can also be an issue when running a Multisite setup. While most plugins work well on WordPress Multisite, some plugins may not work as expected. For example, a plugin that modifies the new user screen in the administrator may not account for the fact that this screen is different when using Multisite. Or a plugin could store data networkwide when you need it to work on a per-blog basis. Again, most plugins work fine, but once in a while you run into a plugin that needs to be fixed, replaced, or altered to work with your specific Multisite setup.

In general, you shouldn’t upgrade your WordPress installation to a Multisite unless you really need multiple websites. If you do need multiple sites, consider the benefits and downsides to hosting them in the same WordPress network.

Multisite Alternatives

Here are some alternatives to consider before using Multisite on your WordPress project.

Multiple Authors or Categories on the Same WordPress Site

If you are primarily interested in organizing your content into separate “sites” or “sections,” consider using multiple blog authors or categories on one WordPress site. If you have multiple authors on the same site, you can update your theme to style each author’s post archive to look like a unique site.

If you’d like to post behind-the-scenes–style content to a separate blog, you can create a post category for that content. You can use filters to keep that content from being included in the main index. You can link to the archive view for that one post category and style it separately to look like a “blog” for your larger site.

Custom Post Types

Another way to organize content to give a “separate sites” feel without actually setting up separate sites is to use CPTs. Similar to using different post categories, you can filter your main index to exclude certain CPTs and treat the archive view of some CPTs as a separate site.

Totally Separate Sites

If you are trying to share content across a few sites or get a few sites to work more seamlessly together, you might consider putting them on the same WordPress Multisite network. Alternatively, you can keep them as separate sites and use the REST API or tools like the WordPress Single Sign-On (SSO) plugin we developed to share content and users across each site (these are covered in detail in Chapter 10).

Use a WordPress Maintenance Service

If you are most excited about the ability to update WordPress themes and plugins from one spot, consider using a WordPress maintenance service. There are many popular ones to choose from. These apps, plugins, and services allow you to manage and update multiple WordPress sites from one dashboard.

The WordPress Command Line Interface can also be used to update multiple WordPress sites at once. For more details, see this good writeup by Phil Banks.

Multitenancy

If you like the concept of a shared repository for WordPress, theme, and plugin files but don’t want the shared database architecture of WordPress Multisite, you should look into multitenancy solutions. A simplistic view of multitenancy for WordPress is that it’s like using a symbolic link for your core WordPress folder and sharing those files across several WordPress installs on the same server or server cluster. In practice, it takes some work to get WordPress to respect this setup. A good place to start to learn more about multitenancy for WordPress are these talks by Cliff Seal on WordPress.tv.

Setting Up a Multisite Network

Once you’ve determined that a Multisite network is what you need, you’ll need to set it up. Although setting up Multisite is not as easy as enabling it in a WordPress setting, it is fairly straightforward. The first thing you should do if you are not setting up a brand-new WordPress installation is to make a backup of your database and file directory.

Open your wp-config.php file in the root of your WordPress directory and add the following piece of code directly under the line that says /* That’s all, stop editing! Happy blogging. */:

define( 'WP_ALLOW_MULTISITE', true );

Refresh your WordPress administrator dashboard and hover over the Tools menu item. On the submenu that opens, click Network Setup. On the Network Setup page you should see a few form fields asking you for the following information:

Subdomain or subdirectory

How do you want to build the subsites on your Multisite network? If you want subdomains like sub.domain.com, choose “subdomain.” If you want domain.com/sub, choose “subdirectory.” You could always use a domain mapping plugin to map any domain you want to, whether a subdomain or subdirectory.

Network title

The name of your Multisite network.

Admin email address

The email of the network administrator, most likely your email address.

Once you have filled out the required information, click the Install button.

You should now be seeing two text boxes. The first text box will contain code that you need to copy and paste into your wp-config.php file, under the line of code you just previously added, beneath the line that says /* That’s all, stop editing! Happy blogging. */:

define( 'MULTISITE', true );
define( 'SUBDOMAIN_INSTALL', false );
define( 'DOMAIN_CURRENT_SITE', 'whatever.com' );
define( 'PATH_CURRENT_SITE', '/' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );
Note

When we talk about WordPress Multisite, we talk about one network with many subsites under that network. The term blog is deprecated in many ways, but still shows up in the Multisite-related database tables and functions. A network is identified by a site_id, and a subsite is identified by a blog_id. Using the word subsite when referring to sites in the network helps to avoid confusion, but you’ll need to get used to figuring out what kind of “site” a piece of code or documentation is referring to.

In this example, we chose to use subdirectories, which is why SUBDOMAIN_INSTALL is set to false. If we chose subdomains, SUBDOMAIN_INSTALL would be set to true.

The second text box contains code that you need to copy and paste into your .htaccess file, which should also be in the root directory of your WordPress installation:

RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*.php)$ $2 [L]
RewriteRule . index.php [L]
Caution

You may have a customized .htaccess file (this could be due to your host or you doing custom things), so make sure you are just replacing the default WordPress rewrite rules. You will also notice, depending on whether you choose subdomains or subdirectories, that the rewrite rules will be different.

Once you have copied and pasted the code from each text box into the appropriate files and saved them on your web server, you can refresh your browser.

You should now be prompted to log in again. Do so with your administrator account username and password. Boom! You should now be running WordPress Multisite as a super administrator, and will have full access to all sites on your network (regular admins have only full access to sites for which they are administrators). Be careful who you hand super administrator rights to.

If you decided to use subdomains instead of subdirectories, there are a couple of extra steps you should take to save you time in the long run. You should set up a subdomain wildcard record on your domain registrar DNS settings page. Remember how, when first installing WordPress, you set the A (Host) record to the IP address of your hosting account? Well, in the same place you did that, you should be able to add a host name of “*” instead of “@” and point it to the same IP address as the “@” record. This acts as a catchall for any subdomains on your main domain. In short, whatever.whatever.com or somethingelse.whatever.com will both be mapped to the same IP address as the main domain.

Depending on your hosting account, you may also need to set up a wildcard subdomain entry to point to the same directory where your main domain is pointing. So register a new subdomain like *.<whatever>.com and point it to the same folder of <whatever>.com.

Why are we doing all this? We set up a wildcard for subdomains so that when we create new sites on the Multisite network they will automatically work. If we didn’t do this, we’d have to manually add each subdomain we create to the domain registrar and to the host. If we set up the subdomain wildcard once, it automatically works for any subdomain sites we create on our Multisite network.

Note

Depending on your host you may still need to do some things manually on the server side. If you are using cPanel and want to point a domain to your Multisite installation, add an add on domain and make sure you point it to the root of your Multisite installation.

Managing a Multisite Network

In your WordPress administrator menu bar, go to My Sites → Network Administrator to administer your new Multisite network. You can also go to <whatever>.com/wp-admin/network/ to get to the network dashboard. The network administrator area looks similar to any other site administrator area on the network. To help keep track of where you are, look for the /network/ at the end of the address bar in your browser, because it can be easy to get confused.

Dashboard

Your network dashboard is set up very similarly to the default dashboard you are used to seeing on a standard WordPress installation except the Right Now widget displays links to quickly add new network sites or users. It also has two text boxes to search for specific users or sites. Just like the regular WordPress dashboard, you can completely customize this network dashboard using plugins or custom code.

Sites

Under Sites, you will manage all of the sites on your network. You can add any number of sites you like and even give your network users permission to create their own sites.

Adding a new site is pretty straightforward; at the top of the sites page, click the Add New button, or, on the Sites submenu, click Add New Link to get to the Add New Site page, where you’ll see the following fields:

Site address

Depending on how you set up your network, the address you enter will either be a subdomain or a subdirectory.

Site title

The title or name of your new site.

Administrator email

The email address of the administrator of your new site. This does not have to be your email address; it could be a client or a user for whom you’re setting up a new WordPress.

Click the Add Site button, and voilà, instant WordPress website. That sure saves a lot of time setting up a brand-new WordPress installation.

Users

All the sites you create on your network will pull from the same users pool. Technically, all users are stored in the wp_users table, and they each have user metadata tying them to one or more sites on your network. From the network users page, you can manage all the users on your sites, make any user a super administrator with rights to manage the entire WordPress Multisite network, and see what sites each user is a member of.

To get to the Add New User page, at the top of the Users page, click the Add New button, or, on the Users submenu, click the Add New link. On the Add New User page, you’ll see the following fields:

Username

The username of the new user you are creating. Remember, with all lowercase and this should have no spaces or special characters.

Email

The email address of the new user you are adding.

Once you click the Add User button, the user you added should receive an email with their username and password, which they can use to log in to the default top-level website with a default role of what you set a new user’s role to be. Adding users this way may not be ideal, as you will have to take another step to add them to specific subsites on your network. Depending on your situation, it might be easier for you to add new users to subsites directly from within that subsite, where you can add a new user the same way you would on a typical WordPress installation. If you try to add a user to a site and that username already exists on the network, you will receive a message indicating that the username already exists. At that point, you can add the user to the site by adding their username to the Add Existing User section and choosing a role and whether to send a confirmation email to that user.

Themes

These are all the themes available in the /wp-content/themes/ directory. You can control all of the themes the sites on your network can use. You must network-enable a theme before a site on your network can use it. If you don’t do so, it won’t even show up as an option to activate on a site’s Appearance → Themes page.

Plugins

These are all of the plugins available in the /wp-content/plugins/directory. You can network-activate plugins so that they will automatically run on all sites on your network, including new sites. Network-activated plugins will not show up on the individual site’s plugins page. In fact, unless you specifically enable the plugins menu on the network settings page (see next section), individual site administrators won’t even see the plugins page.

If you allow each site administrator to manage their own plugins, they will only be able to activate plugins that are already installed; they will not be able to install their own plugins. This is good because you want to know what plugins are available to all of the sites on your network. You don’t want a site administrator to be able to install any plugin they want or a custom plugin that could potentially have a negative effect on other sites on your network.

To add a new plugin at the network level, you would add it the same way you would on a normal installation of WordPress.

Note

Not all plugins should be network-activated. Consult the specific plugin’s documentation when deciding whether to network-activate a plugin or to activate it separately on each site. In general, if it’s only needed on a subset of sites or needs to maintain data or CPTs for each site separately, a plugin should be activated for each site separately.

Settings

These settings are unlike the typical WordPress settings that you can update for a standard WordPress site; these are network-wide settings.

If you click the Settings link on the lefthand administrator navigation menu, you should see the following options:

Operational settings
  • Network name

  • Network administrator email

Registration settings
  • Allow new registrations

  • Registration notification

  • Add new users

  • Banned names

  • Limited email registrations

  • Banned email domains

New site settings
  • Welcome email

  • Welcome user email

  • First post

  • First page

  • First comment author

  • First comment URL

Upload settings
  • Site upload space

  • Upload file types

  • Max upload file size

Menu settings
  • Enable administration menus

Updates

Just as in a standard WordPress installation, you can update core WordPress or outdated plugins and/or themes all from this page. The beauty of a Multisite network is that you can update everything once, and across all the sites on your network. This is far more efficient than running updates on multiple WordPress installs. Update WordPress, plugins, and themes…done and done!

Multisite Database Structure

All sites on a Multisite network share the same database. Enabling WordPress Multisite creates a few new tables in your existing database.

Networkwide Tables

wp_site

The wp_site table stores basic information about your Multisite network like the ID, domain, and path. This table will usually contain only one record. Table 12-1 shows the structure of the wp_site table.

Table 12-1. Database schema for wp_site table
Column Type Collation Null Default Extra

id

bigint(20)

No

None

AUTO_INCREMENT

domain

varchar(200)

utf8_general_ci

No

path

varchar(100)

utf8_general_ci

No

wp_sitemeta

The wp_sitemeta table stores all of the network-wide options or settings. Table 12-2 shows the structure of the wp_sitemeta table.

Table 12-2. Database schema for wp_sitemeta table
Column Type Collation Null Default Extra

meta_id

bigint(20)

No

None

AUTO_INCREMENT

site_id

bigint(20)

No

0

meta_key

varchar(255)

utf8_general_ci

Yes

NULL

meta_value

longtext

utf8_general_ci

Yes

NULL

wp_blogs

The wp_blogs table stores information about each site created on the Multisite network. Table 12-3 shows the structure of the wp_blogs table.

Table 12-3. Database schema for wp_blogs table
Column Type Collation Null Default Extra

blog_id

bigint(20)

No

None

AUTO_INCREMENT

site_id

bigint(20)

No

0

domain

varchar(200)

utf8_general_ci

No

path

varchar(100)

utf8_general_ci

No

registered

datetime

No

0000-00-00 00:00:00

last_updated

datetime

No

0000-00-00 00:00:00

public

tinyint(2)

No

1

archived

enum('0', '1')

utf8_general_ci

No

0

mature

tinyint(2)

No

0

spam

tinyint(2)

No

0

deleted

tinyint(2)

No

0

lang_id

int(11)

No

0

wp_blog_versions

The wp_blog_versions table stores which database schema each site on the network is using. Table 12-4 shows the structure of the wp_blog_versions table.

Table 12-4. Database schema for wp_blog_versions table
Column Type Collation Null Default Extra

blog_id

bigint(20)

No

0

db_version

varchar(20)

utf8_general_ci

No

last_updated

datetime

No

0000-00-00 00:00:00

wp_signups

The wp_signups table also stores information about each user that registers on your network. Table 12-5 shows the structure of the wp_signups table.

Table 12-5. Database schema for the wp_signups table
Column Type Collation Null Default Extra

domain

varchar(200)

utf8_general_ci

No

path

varchar(100)

utf8_general_ci

No

title

longtext

utf8_general_ci

No

None

user_login

varchar(60)

utf8_general_ci

No

user_email

varchar(100)

utf8_general_ci

No

registered

datetime

No

0000-00-00 00:00:00

activated

datetime

No

0000-00-00 00:00:00

active

tinyint(1)

No

0

activation_key

varchar(50)

utf8_general_ci

No

meta

longtext

utf8_general_ci

Yes

NULL

wp_registration_log

The wp_registration_log table stores information about each user that registers on your network, such as user ID, email address, IP address, and blog ID. Table 12-6 shows the structure of the wp_registration_log table.

Table 12-6. Database schema for wp_registration_log table
Column Type Collation Null Default Extra

ID

bigint(20)

No

None

AUTO_INCREMENT

email

varchar(255)

utf8_general_ci

No

IP

varchar(30)

utf8_general_ci

No

blog_id

bigint(20)

No

0

date_registered

datetime

No

0000-00-00 00:00:00

Individual Site Tables

Every site added to your network is automatically given a blog_id when it is created. Each site also creates its own tables, adding its blog_id to each table name. Let’s say we are creating the first additional site on our network besides our main site. It would be given a blog_id of 2, and the following tables would be created in the database:

  • wp_$blog_id_options

  • wp_$blog_id_posts

  • wp_$blog_id_postmeta

  • wp_$blog_id_comments

  • wp_$blog_id_commentsmeta

  • wp_$blog_id_links

  • wp_$blog_id_term_taxonomy

  • wp_$blog_id_terms

  • wp_$blog_id_term_relationships

As you can see, these are the same tables included in a standard WordPress installation except that they have a blog_id in their names. For every new site you create on your Multisite network, these tables will be duplicated with that new site’s blog_id.

Note

In WordPress version 3.5 the UI for links was removed from the administrator but the database table was kept for backward compatibility. If you need the links feature, you can use the Link Manager plugin.

Shared Site Tables

All users on your Multisite network share the same wp_users and wp_usermeta tables.

Users are associated with various sites on the network by a few user meta keys in the wp_usermeta table. If we added a new user to our second site on the network, these meta keys would be created:

  • primary_blog

  • wp_2_capabilities

  • wp_2_user_level

A user can have only one primary_blog but can be tied to multiple sites with the capabilities and user_level meta keys. In the default WordPress installation and on the top-level site of a Multisite network, these meta keys are stored as wp_capabilities and wp_user_level. When you add users to sites on the network, new meta key records are created for each user for the blog_id you are adding them to with whatever role you added them as.

Domain Mapping

By default, any subsites on your Multisite network will use your top-level domain to be either a subdomain or subdirectory unless you specifically set a subsite to use a separate domain.

As long as your DNS is set correctly and you’re pointing the domain to your host and your host has a record of the domain pointing to your Multisite install, mapping a domain should be easy:

  1. Go to your Network dashboard, and then, on the menu, click Sites.

  2. Hover over any subsite on the network and click on the Edit link.

  3. Change the Site Address (URL) field to the domain you want to use, making sure you use the full address: https://<whatever>.com. If you have a SSL certificate for your newly mapped domain, make sure that it is installed and set up.

  4. Click Save to update the page, go to your new domain in the browser, and hopefully put your feet up.

If you encounter any errors about cookies while attempting to log in to the backend of your mapped domain, you may need to update your wp-config.php file by adding the following line of code after the Multisite code you already added.

define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);

Some managed WordPress hosting companies like WP Engine have an API available that you can use to programatically add domains to their DNS. This would save you the time of adding add-on or parked domains to your host’s records manually. With WordPress Multisite integrated with an API like this, all you would need to do is add the new subsite or domain in the WordPress Network Administrator and the API would do the rest, setting up DNS records on the host. For more details, check out the WP Engine API.

Note

Before WordPress 4.5, domain mapping required installing and configuring a third-party plugin to map domains. Now it’s all baked into core WordPress.

Random Useful Multisite Plugins

If a regular WordPress plugin is built correctly, it should work the way it was intended on one or more sites on your network. Developers can also build WordPress plugins specifically for Multisite. The following are a few of the more popular Multisite plugins and what they are built to accomplish.

Gravity Forms User Registration Add-On

Add-On is a great plugin if you want to easily allow users to register to various sites on your Multisite network via a Gravity Forms shortcode or a widget you can place anywhere. It can also be configured to create a new site on your Multisite network when a user creates their account. This could be useful if you want to trigger the creation of a new site for a new user joining your Multisite network.

Member Network Sites Add-On for Paid Memberships Pro

Add-On for Paid Memberships Pro allows you to charge users to create new sites on your network. We cover how to set this up in Chapter 15.

More Privacy Options

Once installed, the WordPress Privacy plugin adds further levels of privacy to your Reading settings. These new levels are Network Users Only, Blog Members Only, and Admins Only, which makes your site visible to only whichever of these groups you choose.

Multisite Global Media

The Multisite Global Media plugin shares a global Media Library across sites on the network. Basically it uses the Media Library of a specific site so any of the sites on a network can access the same shared resources.

Multisite Plugin Manager

If you have a network of sites and you want to give access to site administrators to manage some of the plugins they are using, the Multisite Plugin Manager makes that very easy to manage. The plugin provides a network administrator UI for setting sitewide defaults for each site, you can also override the sitewide defaults for individual sites. There are three main settings for managing your plugins:

  • Auto Activation

  • User Control

  • Mass Activation/Deactivation

Multisite Global Search

Multisite Global Search allows you to search across the multiple sites on your network and receive results from all those sites. This plugin also comes with a built-in widget that can be used to display the search bar in the sidebar. Both the widget and the results page come with a customizable stylesheet. The plugin uses shortcodes, enabling you to insert the search in any templates you choose.

Multisite Robots.txt Manager

Multisite Robots.txt Manager allows you to create custom robots.txt files for each website on the network and then quickly publish those files to the network or a website. This plugin will also instantly add sitemap URLs to all the robots.txt files. In addition, it will automatically detect 404 or old robots.txt files and allows for easy correction once identified.

NS Cloner: Site Copier

There are a few plugins available to copy sites on your network but NS Cloner: Site Copier is a favorite. This plugin is very useful for anyone who needs to duplicate the settings and content from one site to another site on the network. If you are pumping out similar websites, you can create a “template” site all preconfigured exactly how you want it (theme settings, plugin settings, default content, etc.). You can put placeholders into your template site content so when you clone it to make a new site, an action is taken to automatically update these placeholders with whatever values you want. Why start with a blank site where you would have to reconfigure everything? Just clone whatever site you want and use it as a starting point. Save time and money!

WP Multi Network

The WP Multi Network plugin allows one WordPress installation to have multiple networks, with each network having its own subsites. Build a network of networks! Remember how when Multisite is activated, it inserts just one row in the wp_site table? The WordPress Multi Network plugin basically allows you to add new rows to that table and have new subsites set up under a different site_id.

Basic Multisite Functionality

When you activate WordPress Multisite, you can utilize Multisite-specific functionality that was sitting there dormant in WordPress core just waiting to be used.

$blog_id

After reviewing the tables Multisite creates, we know that each site has a unique blog_id. You can use this ID to point WordPress to the site you want to retrieve data from or push data to.

The global variable $blog_id will automatically be set to the site you are on unless changed with the switch_to_blog() function. This variable will be useful when writing custom Multisite functionality:

function wds_show_blog_id(){
    global $blog_id;
	echo 'current site id: ' . $blog_id;
}
add_action( 'init', 'wds_show_blog_id' );

If you are on the top-level site or original site on your network, you should see 1. If you are on the second site you created on your network, you should see 2.

is_multisite()

This function checks to see whether WordPress Multisite is enabled. If you are not running Multisite and try to use one of its functions, you may get an error. Always check that Multisite is enabled before executing Multisite-specific code:

function wds_run_multisite_functions(){
	if ( is_multisite() )
		echo 'Run whatever WordPress Multisite functionality you want!';
}
add_action( 'init' , 'wds_run_multisite_functions' );

get_current_blog_id()

This function returns the blog_id that you are currently on. The function itself is literally two lines of code:

// core function get_current_blog_id
function get_current_blog_id() {
	global $blog_id;
	return absint($blog_id);
}

get_current_blog_id() is located in wp-includes/load.php.

switch_to_blog( $new_blog )

This function switches the current blog to any blog you specify. This function is useful if you need to pull posts or other information from other sites on your network. You can switch back afterward using restore_current_blog(). Autoloaded options and plugins are not switched with this function. This function accepts one parameter, $new_blog, which is a required integer of the ID of the site to which you want to switch.

If we want to switch the site we’re currently on, we could run the following code in any plugin function or theme file:

echo 'current site id: ' . get_current_blog_id() . '<br>';
switch_to_blog(2);
echo 'new current site id: ' . get_current_blog_id();

The code should output something like:

current site id: 1
new current site id: 2

switch_to_blog() is located in wp-includes/ms-blogs.php.

restore_current_blog()

Use this function to restore the current site, after calling the switch_to_blog() function. This function doesn’t accept any parameters.

If we want to restore a switched site, we can run the following code:

echo 'current site id: ' . get_current_blog_id() . '<br>';
switch_to_blog(2);
echo 'new current site id: ' . get_current_blog_id() . '<br>';
restore_current_blog();
echo 'original site id: ' . get_current_blog_id();

The code should output something like this:

current site id: 1
new current site id: 2
original site id: 1

restore_current_blog() is located in wp-includes/ms-blogs.php.

get_blog_details( $fields = null, $get_all = true )

This function gets all the available details of a site and accepts two parameters:

$fields

The ID or name of a specific blog, or an array of blog IDs or blog names. Defaults to the current blog ID.

$getall

Default is set to true to return all available data in the object.

This function returns an object of the following variables:

blog_id

The ID of the blog being queried.

site_id

The ID of the site this blog ID is attached to.

domain

The domain used to access the blog.

path

The path used to access the site.

registered

Timestamp of when the blog was registered.

last_updated

Timestamp of when the blog was last updated.

public

1 or 0 indicating whether the blog is public or not.

archived

1 or 0 indicating whether the blog is achieved or not.

mature

1 or 0 indicating whether the blog has adult content or not.

spam

1 or 0 indicating whether the blog has been marked as spam or not.

deleted

1 or 0 indicating whether the blog has been deleted or not.

lang_id

ID of the language the blog is written in.

blogname

The name of the blog.

siteurl

The URL of the site the blog belongs to.

post_content

The number of posts in the blog.

To display the entire object returned by this function, we would run the following code:

$details = get_blog_details( 1 );
echo '<pre>';
print_r($details);
echo '</pre>';
echo 'Site URL:' . $details->siteurl;
echo 'Post Count:' . $details->post_count;

The code should return a similar object and string:

stdClass Object
(
    [blog_id] => 1
    [site_id] => 1
    [domain] => schoolpress.me
    [path] => /
    [registered] => 2013-03-01 00:23:26
    [last_updated] => 2013-04-01 14:18:59
    [public] => 1
    [archived] => 0
    [mature] => 0
    [spam] => 0
    [deleted] => 0
    [lang_id] => 0
    [blogname] => School Press
    [siteurl] => http://schoolpress.me
    [post_count] => 10
)

This site URL is http://schoolpress.me, and it has 10 posts.

get_blog_details() is located in wp-includes/ms-blogs.php.

update_blog_details( $blog_id, $details = array() )

This function updates the details for a blog and accepts two parameters:

$blog_id

A required integer of the ID of the blog you want to update.

$details

A required array of any of the fields from the blog’s table as keys with any values you want to update.

To mark a particular site as deleted, we would run the following code:

update_blog_details( 2, array( 'deleted' => '0' ) );

update_blog_details() is located in wp-includes/ms-blogs.php.

get_blog_status( $id, $pref )

This function is similar to the get_blog_details() function, except instead of returning an object of all of the fields in the wp_blogs table, it returns the value of one specific field:

$id

A required integer of the ID of the site you want to return a wp_blogs field from.

$pref

A required string of the field name from the wp_blogs table.

To show when the current site was registered, we could run the following code:

echo get_blog_status( get_current_blog_id(), 'registered' );

get_blog_status() is located in wp-includes/ms-blogs.php.

update_blog_status( $blog_id, $pref, $value )

This function is similar to the update_blog_details() function, except instead of updating an array of fields in the wp_blogs table, it updates one specific field:

$blog_id

A required integer of the ID of the site you want to update a wp_blogs field for.

$pref

A required string of the field name from the wp_blogs table you want to update.

$value

A required string of the field value you want to update.

If we wanted to mark the current site as deleted, we could run the following code:

update_blog_status( get_current_blog_id(), 'deleted', '1' );

update_blog_status() is located in wp-includes/ms-blogs.php.

get_blog_option( $id, $option, $default = false )

This function saves you the hassle of using switch_to_blog() and then using the regular WordPress get_option() function or writing a custom SQL query if you want to grab an option from a specific site. This function returns an option value from any site on your network by passing in the following parameters:

$id

A required integer of the ID of the site you want to get an option from. You can pass in null if you want to get an option from the current site.

$option

A required string of the option name you want to get.

$default

Optional string to return if the function does not find a matching option.

To get the admin_email of a particular site, run the following code:

echo 'The admin email for site id 2 is ' . get_blog_option( 2, 'admin_email' );

get_blog_option() is located in wp-includes/ms-blogs.php.

update_blog_option( $id, $option, $value )

This function updates any option for a particular site and accepts three parameters:

$id

A required integer of the ID of the site you want to update an option on.

$option

A required string of the option name you want to update.

$value

A required string of the option value you want to update.

To update the admin_email of a particular site, we would run the following code:

update_blog_option( 2, 'admin_email', '[email protected]' );

update_blog_option() is located in wp-includes/ms-blogs.php.

delete_blog_option( $id, $option )

This function deletes any option from a particular site and accepts two parameters:

$id

A required integer of the ID of the site you want to delete an option on.

$option

A required string of the option name you want to delete.

To delete a custom site option from a particular site, we run the following code:

delete_blog_option( 2, 'wds_custom_option' );

delete_blog_option() is located in wp-includes/ms-blogs.php.

get_blog_post( $blog_id, $post_id )

This function gets a post from any site on the network and accepts two parameters:

$blog_id

A required integer of the blog ID of the site you want to get a post from.

$post_id

A required integer of the post ID of the post that you want to get.

To get the post title of the third post from the second site on our network, we could run the following code:

$post = get_blog_post( 2, 3 );
echo $post->post_title;

get_blog_post() is located in wp-includes/ms-functions.php.

add_user_to_blog( $blog_id, $user_id, $role )

This function adds a user to any site on the network with a specified user role and accepts three parameters:

$blog_id

A required integer of the blog ID of the site you want to add the user to.

$user_id

A required integer of the user ID of the user that you want to add to the site.

$role

A required string of the role you want the user to have.

This function will return true if a user was added successfully; and if not, it will return a WP_Error.

If we wanted to add a specific user to the second site on our network with a role of Administrator, we could run the following code:

add_user_to_blog( 2, 5, 'administrator' );

add_user_to_blog() is located in wp-includes/ms-functions.php.

wpmu_delete_user( $user_id )

This function deletes a user from the entire network, and deletes all posts authored by that user.

$user_id

A required integer of the user ID of the user that you want to delete.

This function returns true if the user was successfully deleted; if not, it returns false.

When Multisite is active, the regular wp_delete_user() function will remove a user from the current site instead of deleting the user entirely. So it is important to make sure you use the wpmu_delete_user() function and hook into both the wp_delete_user and wpmu_delete_user hooks in multisite situations. If you are coding something that needs to run in Multisite or in single-site settings, you can do this with the is_multisite() function first:

if ( is_multisite() ) {
  wpmpu_delete_user( $user_id );
} else {
  wp_delete_user( $user_id );
}

wpmu_delete_user() is located in wp-includes/ms-functions.php.

create_empty_blog( $domain, $path, $weblog_title, $site_id = 1 )

This function creates a new site on the network after making sure it doesn’t already exist. It’s also used by the network admin, to add new sites. It accepts four parameters:

$domain

A required string of the domain of the new blog.

$path

A required string of the path of the new blog.

$weblog_title

A required string of the title or name of the new blog.

$site_id

An optional integer of the site ID associated with the new blog. The default is 1.

If we want to add a new site to our network, we can run the following code:

create_empty_blog( 'someteacher.schoolpress.me', '/', 'Mr. Some Teacher' );

create_empty_blog() is located in wp-includes/ms-functions.php.

Functions We Didn’t Mention

We didn’t cover every Multisite function, but we did cover most of the important ones. Though that depends on what you are trying to do. To find all available Multisite functions, look in the source code! You can find WordPress Multisite functions in the following files:

  • wp-admin/includes/ms.php

  • wp-includes/ms-blogs.php

  • wp-includes/ms-functions.php

For more information, check out the “Multisite functions” section of the WordPress Codex.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.179.186