Home Arrow Icon Knowledge base Arrow Icon WordPress Code Related Arrow Icon How to interact with WordPress Multisite Programmatically

How to interact with WordPress Multisite Programmatically

WordPress Multisite: A Comprehensive Guide for Developers with Code Samples

WordPress Multisite is a powerful feature that allows you to create and manage multiple websites using a single WordPress installation. It offers numerous benefits, such as centralized management, shared resources, and simplified maintenance. In this article, we will explore the concept of WordPress Multisite, discuss its advantages, and provide code samples to help you harness its full potential.

  1. Setting Up WordPress Multisite: To enable Multisite functionality, you need to make a few modifications to your WordPress installation. Follow these steps:

Step 1: Backup your WordPress files and database. Step 2: Open the wp-config.php file and add the following line above the "That's all, stop editing!" comment:

 
define( 'WP_ALLOW_MULTISITE', true );

Step 3: Save the wp-config.php file and refresh your WordPress admin dashboard. Step 4: Go to "Tools" → "Network Setup" and follow the on-screen instructions.

  1. Configuring Multisite Network Settings: After setting up WordPress Multisite, you need to configure its network settings. Here are the steps:

Step 1: Choose between Subdomain or Subdirectory structure:

  • Subdomain Structure:
    • Configure wildcard subdomains (*.yourdomain.com) to point to your WordPress installation.
    • Select the "Subdomains" option during network setup.
  • Subdirectory Structure:
    • No server configuration is required.
    • Select the "Subdirectories" option during network setup.

Step 2: Define network details:

  • Enter the Network Title and Admin Email.
  • Customize the Network Admin and Site Admin email addresses if needed.

Step 3: Complete the installation:

  • Click on the "Install" button.
  • Follow the provided instructions to update your wp-config.php and .htaccess files.
  1. Managing Multisite Network: Once the Multisite is set up, managing the network becomes crucial. Here's how you can navigate through the Multisite network and perform essential tasks programmatically:
  • Accessing Network Admin:
    • To access the network admin dashboard programmatically, you can use the following code:
 
switch_to_network( get_main_site_id() );
  • Creating New Sites:
    • Use the wpmu_create_blog() function to create new sites programmatically:
 
wpmu_create_blog( $newdomain, $path, $title, $user_id, $meta, $site_id );
  • Switching to a Site:
    • To programmatically switch to a specific site within the network, use the following code:
 
switch_to_blog( $site_id );
  • Managing Network Plugins and Themes:
    • You can programmatically enable or disable plugins and themes for the entire network using the activate_plugin(), deactivate_plugins(), and switch_theme() functions.
  1. Multisite-Specific Hooks and Filters: WordPress Multisite provides additional hooks and filters to extend its functionality. Here are a few examples:
  • wp_initialize_site:

    • Fires when a new site is created.
    • Allows you to perform custom actions during site initialization.
  • network_admin_menu:

    • Adds custom menu items to the network admin dashboard.
    • Useful for extending the network's functionality.
  • wpmu_new_user:

    • Triggers when a new user is added to the network.
    • Enables customization of user registration process.

Conclusion: WordPress Multisite is a powerful feature that can streamline the management of multiple websites within a single WordPress installation. By following the steps outlined in this

Here are some code examples:

  1. Programmatically Adding Users to Sites: To add users to specific sites within the Multisite network, you can use the add_user_to_blog() function. Here's an example:
 
$user_id = get_user_by( 'login', 'username' )->ID; $site_id = get_main_site_id(); add_user_to_blog( $site_id, $user_id, 'subscriber' );
  1. Customizing Multisite Registration: If you want to customize the user registration process for Multisite, you can use the wpmu_validate_user_signup filter. Here's an example that checks for a custom registration field named "company":
 
function custom_validate_user_signup( $result ) { if ( isset( $_POST['company'] ) && empty( $_POST['company'] ) ) { $result['errors']->add( 'empty_company', __( 'Please provide your company name.', 'text-domain' ) ); } return $result; } add_filter( 'wpmu_validate_user_signup', 'custom_validate_user_signup' );
  1. Customizing Multisite Site Creation: To perform additional actions during site creation, you can use the wpmu_new_blog action hook. Here's an example that sends a notification email to the site administrator:
 
function send_site_creation_notification( $blog_id, $user_id, $domain, $path, $site_id, $meta ) { $site_url = get_site_url( $blog_id ); $admin_email = get_userdata( $user_id )->user_email; $message = "Congratulations! Your new site is ready. You can access it at $site_url."; wp_mail( $admin_email, 'Site Creation Notification', $message ); } add_action( 'wpmu_new_blog', 'send_site_creation_notification', 10, 6 );
  1. Limiting Site Creation to Super Admins: If you want to restrict site creation to Super Admins only, you can use the wpmu_validate_blog_signup filter. Here's an example:
 
function limit_site_creation_to_super_admins( $result ) { if ( ! is_super_admin() ) { $result['errors']->add( 'super_admin_only', __( 'Only Super Admins can create new sites.', 'text-domain' ) ); } return $result; } add_filter( 'wpmu_validate_blog_signup', 'limit_site_creation_to_super_admins' );

Here are a few more code examples:

  1. Customizing Multisite Site Deletion: To perform additional actions when a site is deleted in Multisite, you can use the wp_delete_site action hook. Here's an example that logs the deletion of a site:
 
function log_site_deletion( $blog_id ) { error_log( 'Site deleted: ' . $blog_id ); } add_action( 'wp_delete_site', 'log_site_deletion' );
  1. Programmatically Switching Themes for a Site: To switch themes programmatically for a specific site within the Multisite network, you can use the switch_theme() function. Here's an example:
 
$site_id = get_main_site_id(); switch_to_blog( $site_id ); switch_theme( 'new-theme' ); restore_current_blog();
  1. Restricting Access to Multisite Administration: If you want to restrict access to the Multisite administration dashboard to Super Admins only, you can use the admin_init action hook. Here's an example:
 
function restrict_multisite_admin_access() { if ( ! current_user_can( 'manage_network' ) && ! ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) { wp_die( __( 'You do not have permission to access this page.', 'text-domain' ) ); } } add_action( 'admin_init', 'restrict_multisite_admin_access' );
  1. Retrieving a List of Sites in the Network: To retrieve a list of sites in the Multisite network, you can use the get_sites() function. Here's an example:
 
$sites = get_sites(); foreach ( $sites as $site ) { echo 'Site ID: ' . $site->blog_id . ', Domain: ' . $site->domain . ', Path: ' . $site->path . '<br>'; }

More Code:

  1. Programmatically Creating a New Site and Assigning a Theme: To programmatically create a new site in Multisite and assign a specific theme to it, you can use the wpmu_create_blog() function along with the switch_theme() function. Here's an example:
 
$new_site_domain = 'newsite.example.com'; $new_site_path = '/'; $new_site_title = 'New Site'; $new_site_admin = 'admin'; $new_site_admin_email = 'admin@example.com'; $theme_to_assign = 'twentytwenty'; // Create the new site $new_site_id = wpmu_create_blog( $new_site_domain, $new_site_path, $new_site_title, get_user_by( 'login', $new_site_admin )->ID ); // Switch to the new site switch_to_blog( $new_site_id ); // Assign the theme switch_theme( $theme_to_assign ); // Restore current site restore_current_blog();
  1. Displaying a List of Sites in a Multisite Network on a Page: To display a list of sites in the Multisite network on a page, you can use the get_sites() function along with a loop to retrieve and output the site information. Here's an example:
 
$sites = get_sites(); foreach ( $sites as $site ) { echo '<h2>Site: ' . $site->blog_id . '</h2>'; echo '<p>Domain: ' . $site->domain . '</p>'; echo '<p>Path: ' . $site->path . '</p>'; echo '<p>Site URL: ' . get_site_url( $site->blog_id ) . '</p>'; }
  1. Creating a Custom Menu in the Network Admin Dashboard: To add a custom menu item to the network admin dashboard in Multisite, you can use the network_admin_menu action hook along with the add_submenu_page() function. Here's an example:
 
function custom_network_menu_item() { add_submenu_page( 'settings.php', // Parent menu slug 'Custom Menu', // Page title 'Custom Menu', // Menu title 'manage_network', // Capability required 'custom-menu', // Menu slug 'custom_menu_page_callback' // Callback function to render the page ); } add_action( 'network_admin_menu', 'custom_network_menu_item' ); function custom_menu_page_callback() { echo '<h1>Custom Menu Page</h1>'; // Add your custom page content here }

Troubleshooting WordPress Multisite:

  1. Common Issues and Solutions:
  • Issue: "ERR_TOO_MANY_REDIRECTS" error when accessing a site in the network.

    • Solution: Check the site's URL settings in the network admin dashboard. Ensure they are correctly configured with the chosen subdomain or subdirectory structure.
  • Issue: Missing or incorrect Rewrite Rules.

    • Solution: Regenerate the Rewrite Rules by visiting the "Settings" → "Permalinks" page in the network admin dashboard and clicking the "Save Changes" button.
  • Issue: "404 Page Not Found" errors on subdomain-based Multisite.

    • Solution: Ensure that wildcard subdomains are correctly set up to point to your WordPress installation. Contact your hosting provider for assistance if needed.
  1. Enabling Debugging for Troubleshooting: To enable debugging in WordPress Multisite and get more detailed error messages, you can add the following code to the wp-config.php file just above the "That's all, stop editing!" comment:
 
define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); define( 'WP_DEBUG_DISPLAY', false );
  1. Troubleshooting Plugin Conflicts: If you encounter issues with plugins in your Multisite network, follow these steps to troubleshoot:
  • Disable all plugins on the network and check if the issue persists. If not, reactivate each plugin one by one to identify the conflicting plugin.
  • Use the network_admin_notices action hook to display an error message if a conflicting plugin is active:
 
function check_for_plugin_conflicts() { if ( is_plugin_active( 'conflicting-plugin/conflicting-plugin.php' ) ) { echo '<div class="error"><p>Conflicting Plugin is active. Please deactivate it.</p></div>'; } } add_action( 'network_admin_notices', 'check_for_plugin_conflicts' );
  1. Troubleshooting Theme Issues: If you encounter issues with themes in your Multisite network, follow these steps to troubleshoot:
  • Temporarily switch to a default theme (e.g., Twenty Twenty-One) to check if the issue is related to the current theme.
  • Use the network_admin_notices action hook to display an error message if a specific theme is causing issues:
 
function check_for_theme_issues() { if ( get_stylesheet() === 'your-theme-folder/your-theme-style.css' ) { echo '<div class="error"><p>Theme is causing issues. Please switch to a different theme.</p></div>'; } } add_action( 'network_admin_notices', 'check_for_theme_issues' );
  1. Inspecting Database Tables: If you suspect issues with the Multisite database tables, you can use the get_blog_prefix() function to retrieve the table prefix for a specific site and then inspect the corresponding tables.
 
$site_id = 2; // Replace with the desired site ID $table_prefix = get_blog_prefix( $site_id ); // Example: Inspect the posts table for site ID 2 $posts_table = $table_prefix . 'posts'; $results = $wpdb->get_results( "SELECT * FROM $posts_table" );