WordPress 5 Cookbook

4 (2 reviews total)
By Rakhitha Nimesh Ratnayake
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Setting Up WordPress and Customizing Settings

About this book

WordPress has been the most popular content management system (CMS) for many years and is now powering over 30% of all websites globally. With the demand for WordPress development and skilled developers ever-increasing, now is the best time to learn WordPress inside out.

This book starts with simple recipes for configuring WordPress and managing basic platform features. You’ll then move on to explore how to install and customize WordPress plugins, widgets, and themes. The next few chapters cover recipes for content and user-management-related topics such as customizing the content display, working with content types, using the new Gutenberg editor, and customizing editorial workflow for building advanced blogs. As you advance, you’ll learn how to use WordPress as an application framework as well as a platform for building e-commerce sites. This WordPress book will also help you optimize your site to maximize visibility on search engines, add interactivity, and build a user community to make the site profitable. Finally, you’ll learn how to maintain a WordPress site smoothly while taking precautions against possible security threats.

By the end of the book, you’ll have the tools and skills required to build and maintain modern WordPress websites with the latest technologies and be able to find quick solutions to common WordPress problems.

Publication date:
March 2020
Publisher
Packt
Pages
660
ISBN
9781838986506

 

Setting Up WordPress and Customizing Settings

In this chapter, we will begin by focusing on the basic setup and configuration options that are built into the default WordPress Content Management System (CMS). We will be going through basic setups such as managing media files, discussions, privacy policies, and permalinks. Also, we will look at the process of setting up and using multisite environment features within WordPress. The goal of this chapter is to teach you how to prepare basic WordPress tools so that you can manage advanced tasks in the upcoming chapters.

In this chapter, we will learn about the following recipes:

  • Managing media files with the Media Library
  • Setting up the discussion process
  • Creating and managing a privacy policy
  • Customizing default WordPress emails
  • Configuring a Permalinks structure
  • Setting up WordPress Multisite
  • Creating a new site on a multisite network
  • Managing multisite themes and plugins
  • Cloning a site in a multisite installation
 

Technical requirements

Code files are not required for this chapter.

 

Managing media files with the Media Library

The built-in Media Library is where you store all your images, videos, audio, and other files. We can directly add media to the library for later use or we can directly add them to posts. Existing features include the ability to edit and search media files, which makes life easier for the administrator.

In this recipe, we are going to use the Media Library to upload and organize files while executing the built-in features on media files.

Getting ready

You need to have an existing WordPress installation to work with these recipes. The necessary features are available on the WordPress dashboard.

How to do it...

To start adding media files, follow these steps:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click on the Media menu.
  3. You will get a screen similar to the following Media Library screen. The list will be empty since you don't get any media files with a default WordPress installation:

  1. Click on the Add New button to upload new files. You will get a screen similar to the following:

  1. Drag some image files from your computer and drop them into the Drop files here area. Alternatively, you can select them using the Select Files button.
  1. Once you've selected some files, WordPress will automatically upload them and list them at the bottom of the screen, as shown in the following screenshot:

  1. Now, visit the Media | Library section and click the List icon to see the uploaded files appear at the top of the list as shown in the following screenshot.

  1. You can continue this process to add any number of allowed files to the Media Library.

Now, we can take a look at the common operations inside the Media Library.

To edit a file, we have to go through the following steps:

  1. Hover the mouse over the top of a file from the list. Here, you will see the Edit link, as shown in the following screenshot:

  1. Click on the Edit link. This will open the following screen so that you can edit files:

  1. You can add a title, alternative text, a caption, and a description. After you've done this, click the Update button to save the details.

When editing an image, you will get another button called Edit Image. Clicking that will take you to the image editing screen, as shown in the following screenshot. You can use this screen to crop, scale, or rotate an image and save it to the library:

To Crop, Scale, and Rotate an image, we have to go through the following steps:

  1. Go to the Scale Image section and reduce the width and height according to your needs.
  2. Click the Scale button to resize the image.
  3. Go to the image under the crop buttons on the left and click on it.
  4. Then, drag it to select the area for cropping, as shown in the following screenshot:

  1. Click the Crop button to crop the image.
  2. Click the Rotate buttons alongside the Crop button to rotate the images either left or right.

To delete a file, we have to go through the following steps:

  1. Hover the mouse over the top of a file from the list. By doing this, you will see the Delete Permanently link.
  2. Click on the Delete Permanently link to delete a file.
  3. Click OK in the popup alert box to delete the file from the library.

To attach a file to a post, we have to go through the following steps:

  1. Select a file from the list and click the Attach button in the Uploaded to column. You will see a screen similar to the following:

  1. Select the post you want and click the attach button to attach the file to a specific post. You will see an output that looks similar to the following:

You can also view and search for files from the Media Library. The files in the Media Library can be used when creating and editing posts and pages.

How it works...

Once a new file has been uploaded from the media uploader, it will be saved in the wp-content/uploads folder of your WordPress site with a unique file name. Inside the uploads folder, there will be several folders for each year and month. If we upload the file in January 2020, the path to the file will be wp-content/uploads/2020/01. If we upload an image file, WordPress will automatically create several images with different sizes called thumbnail, medium, and large. Then, WordPress will use the appropriate size in different places such as an archive page, single post, and so on. The original image will be also stored along with these resized versions.  

Also, details about these files will be stored in the wp_posts table as a special post type called attachment. The following screenshot shows how the attachments are stored in the database using the phpMyAdmin tool:

If you are not familiar with working with a database, use the Appendix to understand the process of using a database management tool to view this data.

The Media Library lists the available files by executing database queries on the wp_posts table.  

Then, we looked at editing files. The normal editing process allows you to add a caption and description for the file. However, WordPress provides additional editing features for images. We used the scaling, cropping, and rotating features for images. Once these features have been applied and saved, WordPress will create another set of images with different sizes inside the same folder path. The Media Library will only display the latest modified version of the image. Other versions before the last edit will be discarded. 

Next, we looked at the process of deleting files. Once we click the Delete Permanently link for a media file, it will be removed from the database and the file will be deleted from the path inside the wp-content/uploads folder. If we are deleting an image, it will remove all versions of the image, including the images that were created with each edit. 

Finally, we looked at the process of attaching a file to a post. Both posts and attachments are stored in the wp_posts table in WordPress. Once a media file has been attached to a post, the media file record in the wp_posts table will be updated to include the ID of the post as a parent of the media file. So, WordPress will use the parent ID to identify whether a file is attached to a post/page. If we detach the file, the parent ID will be set to 0 to remove the relationship. 

There's more...

In the previous section, we looked at the process of uploading files directly to the Media Library. We can also upload files directly to posts/pages. These files will also be added automatically to the Media Library. Let's see how we can add a file to a post and get it in the Media Library:

  1. Click on the Posts menu.
  2. Click the Add New button to create a new post.
  3. Click the plus (+) sign on the following screen to add a block in the post-editing screen:

  1. Type File to find the file block.
  2. Click File block to upload a file.
  3. Click the Upload button and select a file from your computer to upload it.

The file will be uploaded and added to the post. Also, the file will be listed in the Media Library as being attached to the newly created post.

 

Setting up the discussion process

In modern sites, rather than provide static information for reading we want people to interact with the site. Enabling discussions in posts and pages is the first and simplest step to begin user interaction on sites. WordPress provides a separate section that you can use to manage discussion-related settings.

In this recipe, we are going to look at the available settings and how to configure them properly to optimize the discussion process.

Getting ready

Twenty Twenty theme should be activated before starting this recipe. WordPress 5.3.2 and higher versions have the Twenty Twenty theme activated by default. If you have changed the theme, use the following steps to activate it.

  1. Login to Dashboard as an administrator
  2. Click Appearance menu item on the left menu
  3. Click Activate button of Twenty Twenty theme

Now, you are ready to start this recipe.

How to do it...

The process of configuring discussion settings is site-specific. Follow these steps to identify and configure the most common discussion settings:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click on the Settings menu.
  3. Click on the Discussion option.
  1. You will get a screen similar to the following, which shows all the available settings related to discussion:

  1. Find the following settings and keep or change the values based on your preferences. These settings will be explained in the How it works... section:
    • Users must be registered and logged in to comment
    • Comment author must fill out name and email
    • Automatically close comments on articles older than [x] days  
    • Email me whenever anyone posts a comment
    • Email me whenever a comment is held for moderation
    • Before a comment appears Comment must be manually approved
    • Before a comment appears Comment author must have a previously approved comment
  2. Click the Save Changes button to apply the settings.

Now, you can view a post from the frontend of your site to see the comments section, as follows:

The commenting section will be displayed based on the settings you selected in the previous steps. Now, the user can use this form to submit comments. You can view the submitted comments by logging in to the Dashboard as an administrator and clicking the Comments menu item on the left menu.

How it works...

Once the settings have been saved, WordPress will change the built-in comments section so that it matches your preferences. Each of the available settings plays a different role in handling discussions. We have only selected settings that are the most important for any site. Let's take a look at how these settings work:

  • Users must be registered and logged in to comment (Signup has been disabled. Only members of this site can comment.): By default, any user visiting the site will be able to comment by providing their name and email. However, in certain scenarios, you may want to restrict this to members only. Avoiding a lot of spam comments and building a member-specific private site are two such scenarios where this is a good idea. Once this setting has been enabled, users won't be able to comment unless they have registered and logged in to the account.
  • Comment author must fill out name and email: This is enabled by default, and makes the name and email fields compulsory in the comment form. Enabling this setting allows you to identify the users rather than having a lot of unnecessary comments from random people. Disabling this setting could increase spam comments. Hence, you should be careful when changing this setting.
  • Automatically close comments on articles older than x days: This setting specifies whether to close comments after a certain number of days. This is disabled by default. We can enable this setting and define the period in most sites to avoid spending time moderating comments on old posts. Once enabled, the comment form will be removed after specified days and will only allow visitors to view the content.
  • Email me whenever anyone posts a comment: This setting is enabled by default and the site admin will get an email for each comment. This could be unnecessary overhead in many simple sites where you don't need immediate comment approvals. Therefore, you can disable the notification if real-time comment approval is not important in your context.
  • Email me whenever a comment is held for moderation: This is similar to the previous setting, but this will notify you when you need to approve/decline a comment. It's better to disable it unless timely comment approval is very important in your context.
  • Before a comment appears Comment must be manually approved: This is disabled by default and all comments are approved automatically. Once you start getting a lot of spam or unnecessary comments on your site, you can enable this option. Once enabled, the comment will be only visible to the person who commented and admins, until it's approved to be displayed to the public.
  • Before a comment appears Comment author must have a previously approved comment: This setting is similar and enabled by default. An admin has to approve the first comment from a specific user. After that, the user will be able to post more comments without requiring moderation.

There is no fixed setup for these settings. Due to this, you should check the requirements of the site and adjust them accordingly to provide the best discussion process.

There's more...

In this recipe, we looked at the first part of the discussion settings screen. There is also another important section on this screen called Comment blacklist. Once a site is open for user comments, anyone can come and add any content they like. Sometimes, it might not be related to your post and sometimes, it could be just spam content promoting their own products or services. In order to limit these unnecessary comments, we can use the Comment Blacklist setting to add the words we want to block. Once WordPress detects comments with one of these words, it will trash the comment. This is useful to avoid spam comments and reduce the time spent moderating these comments.

In this recipe, we looked at the discussion-related settings and applied them globally to all parts of the site. However, we have the ability to enable or disable discussion on specific posts by using the Settings section within each post. The following screenshot shows the discussion settings inside the post:

From here, we are allowed to enable/disable comments, pingbacks, and trackbacks for individual posts. However, other settings can be applied globally to each and every post.

 

Creating and managing a privacy policy

Privacy is one of the main concerns for users when using a new website or service. Modern websites use personal data as well as a user's behavior to improve their features and user-friendliness. The privacy policy on a website defines what kind of data is collected from users and how the data will be used. With the introduction of the GDPR regulation by the European Union, privacy policies have become a mandatory requirement for most sites.

The latest versions of WordPress contains a built-in privacy policy page where admins can customize the content according to their preferences and display it on the site.

In this recipe, we are going to look at the default privacy policy feature and its configuration.

Getting ready

Special preparation is not required for this recipe. The necessary features are available on the WordPress dashboard.

How to do it...

Creating a privacy policy is as simple as configuring and saving a single setting in the Dashboard. Follow these steps to create a Privacy Policy page and identify different ways of creating privacy policy content:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click on the Settings menu.
  3. Click on the Privacy option.
  4. The Privacy Settings screen can be seen in the following screenshot. Here, we have to configure the Change your Privacy Policy page setting. By default, a page called Privacy Policy will be selected:

  1. Select the default page or select one of the existing pages and click the Use This Page button to use it as the privacy policy. Also, you have the option of creating a new page and assigning it as a privacy policy page by using the Create New Page button.
  2. Click the Edit link to edit the content of the privacy policy page. You will get a screen similar to the following:

  1. Modify the content of the default privacy policy so that it suits the requirements of your site. Then, click the Publish button to save changes.

Now, you can view the privacy policy on the frontend by clicking the View link of the Privacy Policy page. You will see the default Privacy Policy content or customized content based on the options you chose previously.

How it works...

We have three ways of assigning the Privacy Policy page in WordPress, as follows:

  • WordPress provides a built-in page called Privacy Policy with the default content. The page is saved as a draft. Once we select the default page and click the Use This Page button, the built-in page will be used as the Privacy Policy page. You will have to Publish the page as it's in draft status by default.
  • We have the option to choose a custom page and click the Use This Page button. In this case, you will have to write the entire privacy policy from scratch on a new page before assigning it to this setting. The default privacy policy content of WordPress will not be used.
  • We have the ability to create a privacy policy on a new page. In this case, you have to click the Create New Page button. Once clicked, WordPress will publish a new page with default privacy policy content. You can adjust the content and update the page. Now, the new page will be used as the privacy policy and the default privacy policy page will still exist as a draft that includes the original privacy policy content.

Once the privacy policy has been added using one of these methods, we can let visitors view the Privacy Policy as a normal WordPress page.

 

Customizing default WordPress emails

Email notifications in a site help users and administrators keep track of the site's activities and urges them to take action. WordPress provides a set of built-in email templates for major actions. More often than not, we will need to customize the content of these default email templates based on the type of the site and its requirements. As of version 5.3.2, WordPress doesn't offer features for customizing email content from the dashboard. Using the built-in filter hooks is the only way to customize the content. So, non-technical users may face difficulties when changing these emails.

In this recipe, we are going to use the Better Notifications for WordPress plugin to customize the default emails. We will learn how this plugin can be used to introduce and customize emails for actions not provided by WordPress.

Getting ready

You have to install the Better Notifications for WordPress plugin to execute this recipe. To do this, follow these steps:

  1. Click Plugins | Add New.
  2. Search for Better Notifications for WordPress in the Search plugins field.
  3. Once the plugin appears, click the Install Now button.
  4. Finally, click the Activate button to activate the plugin.

How to do it...

Follow these steps to create a new notification type and customize the content of WordPress emails:

  1. Log in to the WordPress Dashboard as an administrator.
  2. Click the Notifications menu that's generated by the plugin.
  3. Now, you will get a list of notifications that have been created by the plugin, as shown in the following screenshot. At this stage, it will be empty as we haven't created any notifications:

  1. Click the Add New menu item to create a notification and customize the content of WordPress emails. You will get a screen similar to the following:

  1. Select the New User Registration – For User option under the Notification For setting.
  2. Fill in the email formatting, subject, and content for the email. You can use the Insert Default Content button to view the default template for this email and then modify it based on your requirements.
  3. Click the Save button to save the new template for user registration emails.

You can follow the same process for other email templates. Once a new user registers through the site, an email that includes customized content will be sent to the user's email.

How it works...

The Better Notifications for WordPress plugin lists all the available email notifications, including default emails and custom emails, that are created by using existing WordPress hooks. The options that are listed in the Admin and Transactional sections are available by default in WordPress.

Let's take a look at the available settings:

  • Email Formatting: This setting is used to define whether the email will be in plain text or HTML format.
  • Subject: This will be the subject of the email that's sent by WordPress.
  • Message Body: This will be the content of the email that's sent by WordPress.

Once WordPress tries to send an email, this plugin looks in its notification table for an appropriate notification for the scenario. If a matching notification is found, the plugin will override the default WordPress email with all the settings. So, the user, in this case, will get a custom email that's been configured by the plugin.

There's more...

In the previous section, we only looked at the settings that are available for all the email templates. However, there are more settings that work only with certain email templates, such as admin emails and custom emails.

Let's look at additional available settings for specific templates:

  • Additional Email Fields: Once this setting is enabled, you will get a new set of settings to define, including the name, email, reply to email, and CC and BCC emails. By default, you will have to use WordPress filter hooks to define these values, which is difficult for a non-technical administrator. With this plugin, you can input all these values to make the email more user-friendly and send it to additional users.
  • Send To: These settings are used to define specific user roles or users that will receive this email. So, we can conditionally set which users will get the notification.
  • Except For: This setting implements the opposite of the previous setting, where we can define which roles or users will not receive this email. Once this setting is used, every user except those defined here will receive the notification.

You can configure multiple email notifications for the same email type with different conditions and send different emails to different types of users.

 

Configuring the structure of permalinks

A permalink refers to the permanent unique link to a certain post, page, or custom screen on your WordPress site. Most existing search engines give high priority to the words in the permalink when ranking a certain URL in search results. So, it's important to set up permalinks properly to make them user-friendly as well as search engine-friendly. WordPress provides in-built permalink structures and allows you to define your own custom structures.

In this recipe, we are going to look at the process of changing the default permalink structure and configuring a search engine-friendly permalink structure.

Getting ready

Special preparation is not required for this recipe. The necessary features are available on the WordPress dashboard.

How to do it...

The WordPress installation comes with a built-in permalink structure. Follow these steps to customize the permalink structure according to your needs:

  1. Open one of the posts on your site and check the post's URL in a browser.
  2. Log in to the WordPress Dashboard as an administrator.
  3. Click on the Settings menu.
  4. Click on the Permalinks option.
  5. The default permalink section can be seen in the following screenshot. Change the permalink structure setting to Post name:

  1. Click the Save Changes button to update the permalinks.
  2. Open the post in step 1 and check the modified URL for the same post in the browser.

Now, you will see that the URL has been modified to remove the date-related part, as shown in the preceding screenshot.

How it works...

The permalink structure is stored in the wp_options table with a key called permalink_structure. The default value for this option is /%year%/%monthnum%/%day%/%postname%/.

Once the settings have been saved, this value will be updated to the selected value. Once the Post name has been selected, the value will be /%postname%/.

WordPress doesn't understand the pretty URLs provided by these custom permalink structures. So, the rewrite modules for different web servers convert this pretty URL into the default URL with the post ID.

In old versions, WordPress used to have a Plain option with a post ID as a query parameter. This structure was not user-friendly, nor search engine-friendly. So, the latest versions come up with Day and name as the default option. This is considered a good permalink structure compared to using query parameters due to the use of user-and search engine-readable values instead of a plain numeric ID. However, dates in the permalink indicate whether the content is old or new. Hence, there is a chance that you can skip certain resources on your site if you think the content is not up to date. As a solution, we use a post-name-only option to optimize it for readers as well as search engines.

There's more...

Once the permalink structure has changed, the URLs of your site will also change immediately. However, changing the permalink structure is not an ideal option for sites with existing data. The URLs you have used in other services and social media will stop working and will return 404 pages. You will need to do extra work to get them working using 301 redirects. So, it's recommended you set up permalinks up-front to avoid extra work and issues with old URLs not working.

WordPress provides features such as custom post types and custom rewrite URLs that require you to update the existing permalink structure. Once a new custom post type of or rewrite URL has been added, permalinks will not be updated automatically. Hence, these custom URLs won't be working immediately. You will have to update the permalinks manually by using custom code or visiting the Settings | Permalinks section. You don't have to change the permalink structure. Clicking the Save button will update the permalinks on the database for new rewrite rules and they will start working without 404 errors.

 

Setting up WordPress Multisite

WordPress Multisite is an in-built feature that's disabled by default. This feature allows us to manage multiple sites as a network by sharing the same WordPress installation, plugins, themes, and some of the core database tables. The advantage of Multisite is its ability to manage all your sites in a single dashboard, thus allowing you to make updates on all sites at once.

The process of enabling Multisite is not a straightforward task and hence could be difficult for a beginner. It involves changing core WordPress files and hence needs to be executed carefully.

In this recipe, we are going to configure the necessary settings to enable the Multisite feature in WordPress and get the installation ready for creating new sites.

Getting ready

We can enable the Multisite feature on our existing WordPress site that we used for previous recipes. However, we recommend that you create another WordPress installation in order to execute this recipe as we need a single-site installation to execute the recipes in the remaining chapters.

You will edit core WordPress files and htaccess files in this recipe. Open the code editor and make sure that you have access to the theme files in your local or external WordPress installation.

How to do it...

Follow these steps to enable the Multisite feature in WordPress:

  1. Open the wp-config.php file in the root WordPress installation folder using the code editor.
  2. Add the following line to the wp-config.php file before That’s all, stop editing! Happy publishing in order to enable Multisite feature:
define('WP_ALLOW_MULTISITE', true);
  1. Upload the modified wp-config.php file.
  2. Log in to the WordPress Dashboard as administrator.
  3. Click the Tools menu.
  1. Click the Network Setup option to get the multisite configuration screen, as shown in the following screenshot:

  1. Add values for the Network Title and Network Admin Email fields. Then, click the Install button to install the multisite network.
  2. You will get a screen similar to the following, which contains details that you can use to configure the network:

  1. Back up the wp-config.php and .htaccess files.
  2. Copy the following content. This code is used to configure the multisite settings:
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'www.cookbook.wpexpertdeveloper.com');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
  1. Add the copied content to the wp-config.php file after the line we added in step 2 of this recipe.
  2. Copy the following content. This code is used to configure the rewrite rules for multisite:

# BEGIN WordPress
<IfModule mod_rewrite.c>
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]
</IfModule>

# END WordPress
  1. Replace the content in the htaccess file with the copied content.
  1. Log in again with administrator credentials. You will see the following screen:

You will see a new menu item called My Sites with a submenu item called Network Admin. These menu items confirm that the multisite features have been enabled on the site.

How it works...

Once the WP_ALLOW_MULTISITE setting has been added to the wp-config.php file, you will see a new menu item in the Tools menu called Network Setup. The settings provided after Network Installation allows WordPress to identify this as a multisite network by defining domain, path, site, and blog IDs. Let's look at the constants that are used in this process:

  • MULTISITE: This setting enables the Multisite features in WordPress.
  • SUBDOMAIN_INSTALL: We used false for this setting as we will be using subfolders to create sites in the network. We can set it to true when we want to use separate subdomains for each site in the network.
  • DOMAIN_CURRENT_SITE: This is the domain of your main site before enabling the network features.
  • PATH_CURRENT_SITE: This is the path of the main site so we use / to identify it as the root folder.
  • SITE_ID_CURRENT_SITE: This is the ID of the parent site. It will be 1.
  • BLOG_ID_CURRENT_SITE: This is the ID of the blog within the network. It will be 1 for the main site.

The URL structure that's used to handle a multisite network is different from a single-site network. Therefore, we need to make modifications to the htaccess file so that it supports redirection rules for multiple sites. The Rewrite Rules that are provided after Network Installation allow WordPress to handle the requests for each site. Let's consider the following code:

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

The first three lines are common to single and multisite installations. This code enables the rewrite engine, sets relative paths, and makes sure every request is passed through the index.php file. The following lines are also common to multisite and single-site networks:

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

The preceding lines are executed when a file or directory is requested. In such a case, the request goes through the rewrite engine, which stops rewriting:

RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]

These three lines are multisite-specific and check the availability of some content before wp-admin, wp-contentwp-includes, or any PHP file and rewrites it. The complete code in htaccess makes sure that requests for each site are handled properly with valid rewrites.

Basically, we are enabling an already available feature in WordPress using the settings in the wp-config.php file.

There's more...

A multisite installation uses different database structures compared to single-site installations. Once you've set up the network, an extra set of basic database tables will be created so that you can manage the sites in the network. This means that the table count will increase to 19 from the default 12 tables. 

The following multisite-specific tables are available:

  • wp_blogmeta: Additional details for each site in the network will be stored in this table.
  • wp_blog: This table contains the details of the sites. Each site in the network will be considered as a blog and will have one row in this table.
  • wp_blog_versions: This table stores the database version of each site.
  • wp_registration_log: This site contains the administrator user details for each site.
  • wp_signups: This table stores the user registration details for each site in the network.
  • wp_site: This table stores the site address and path for each site.
  • wp_sitemeta: This table stores additional details about the sites in the wp_site table.

These seven tables are only used to handle the settings and users for the entire network. To handle data for each site, we will need a set of duplicate tables for each site. We are going to look at these tables later in this chapter.

 

Creating a new site in a multisite network

Once a multisite network has been set up, creating a new site is a relatively simple task. As a super admin, we can add the sites manually or let users create their own sites in the network. Usually, this feature is used on a set of fixed sites to share the same resources. Therefore, a super administrator is responsible for creating additional sites. However, there are scenarios where you might offer a service where users can register their own sites and use the products and services you provide.

This recipe shows you how to manually add a new site to the network and configure the basic settings.

Getting ready

The Multisite feature should be set up properly with all required database tables.

How to do it...

In a multisite, a super administrator can create new sites or let users create their own sites. Follow these steps to create a new site as a super administrator:

  1. Log in to the WordPress Dashboard as a super administrator.
  2. Click My Sites | Network Admin from the top menu.
  3. Click the Sites menu item to display the available sites in the network, as shown in the following screenshot. The default installation will be displayed as the main site:

  1. Click the Add New button to create a new site on the network.
  1. You will get a screen similar to the following. Fill in the Site Address, Site Title, Site Language, and Admin Email settings for the new site. The address should be unique within the network:

  1. Click the Add Site button to create the site.
  2. Click the Sites menu item to display the available sites, as shown in the following screenshot:

  1. Click the Visit link to view the frontend of the site.

You can follow the same process to add more sites to the network.

How it works...

The new site will be saved in a database table called wp_blogs, along with its status. This process will create 10 new database tables in order to manage the new site. These tables will be prefixed with a numeric ID. So, you will see database tables starting with wp_2_ prefix for this site. These tables will handle the data for the new site while using the wp_users table in common, for all the sites.

In the site creation process, WordPress will check the availability of the site admin email in the database. If a user is not found, a new admin user will be created with the specified email address. The username and password reset link will be emailed to this email address. Then, the site administrator can log in and start configuring the sites based on the requirements.

 

Managing multisite themes and plugins

The process of installing and activating plugins and themes is straightforward in single-site installations. However, it's slightly more complex in multisite environments.

In this recipe, we are going to look at the process of managing plugins and themes on individual sites and using them across all sites.

Getting ready

The Multisite feature should be set up properly with all the database tables. In a multisite, only a super administrator is allowed to install new plugins and themes. The administrators of each site in the network only have permission to activate the available plugins or themes.

How to do it...

Follow these steps to install new plugins for a multisite network:

  1. Log in to the WordPress Dashboard as a super administrator.
  2. Click My Sites | Network Admin from the top menu.
  3. Click the Plugins menu item to display the available plugins in the network.
  4. Click the Add New button to install a new plugin for the network.
  5. Search for a plugin from the WordPress plugin directory.
  6. Click the Install Now button to install the plugin for the network.

In a multisite, plugins can be activated across all sites or only on individual sites. Let's start with the process of activating a plugin on the entire network:

  1. Click on My Sites | Network Admin from the top menu to log in to the site as a super administrator.
  2. Click on the Plugins menu item to display the available plugins in the network, as shown in the following screenshot:

  1. Select a plugin and click it's associated Network Activate link to activate the plugin.

Let's activate a plugin on individual sites:

  1. Log in to the Dashboard of a specific site as an administrator.
  2. Click on the Plugins menu item to display the available plugins in the network, as shown in the following screenshot:

  1. Select a plugin and click its associated Activate link to activate it. You can only activate/deactivate the plugins that haven't been activated across the network.

Follow these steps to install a new theme to a multisite network:

  1. Log in to the WordPress Dashboard as a super administrator.
  2. Click My Sites | Network Admin from the top menu.
  3. Click the Themes menu item to display the available themes in the network.
  4. Click the Add New button to install a new theme onto the network.
  5. Search for a theme from the WordPress theme directory.
  6. Click the Install button to install the theme onto the network.

In a multisite, a theme can be activated on individual sites. Let's start with the process of activating a theme:

  1. Click My Sites | Network Admin from the top menu while logged in as a super administrator.
  1. Click on the Themes menu item to display the available themes in the network, as shown in the following screenshot:

  1. Select a theme and click the Network Enable link to enable the theme for all sites.
  2. Log in to the Dashboard of a specific site as an administrator.
  3. Click on the Appearance | Themes menu item to display the available themes for the site.
  4. Select a theme and click its associated Activate button to activate the theme.

Now, you have installed and activated a WordPress plugin.

How it works...

Plugins and themes in a multisite environment work differently from a single-site installation. First, we are going to look at the plugins in a multisite environment.

In a multisite, plugins are shared across all the sites. So, only the super administrator has permission to install new plugins. Once a plugin has been installed, the files will be located inside the common wp-content/plugins folder for the WordPress installation. It will be available for all the sites in the network.

Using the Network Activate option activates the plugin on all the sites in the network. So, the administrators of individual sites will not be able to activate/deactivate the plugin on their site. However, administrators of each site will be able to adjust the settings of the plugin for a specific site.

The plugins that are not activated across the network will be listed on individual sites with an activate/deactivate option. The administrator of each site can activate the plugin when necessary and it won't affect the other sites in the network.

Themes work differently from plugins. In a multisite, the super administrator can use the Network Enable option to make the theme available to the entire network. However, this action doesn't activate the theme on all sites in the network. Once the theme has been network-enabled, site administrators can activate it on their individual sites. Unless a theme has been enabled, it won't be visible in the themes section for subsites.

There's more...

There are other important things to consider in the Multisite plugin and theme management process in multisite. In this section, we are going to look at how we can handle version updates as well as how multisite-compatible plugins work compared to regular plugins.

Regularly updating plugins and themes is an essential task in order to keep up to date with the latest features and avoid potential security threats. It's a time-consuming process, even in a single-site installation. Manually updating themes and networks on individual sites of the network will be a highly time-consuming and sometimes impractical task in networks with a large number of sites. However, the WordPress Multisite feature is designed to update plugins and themes from the network plugins and themes section. Once a plugin or theme has been upgraded from the network, it will be automatically upgraded on all the sites on the network.

We need to be cautious when using plugins on multisite environments as not all plugins are fully compatible with multisite. The plugins that use the core database tables have more chance of being incompatible as each site uses a different set of tables with the respective site ID. When a certain plugin doesn't use the blog ID, all the sites in the network will use the main site's database tables of the main site. This is only one way of being incompatible in a multisite environment.

So, we have to check whether plugin developers provide multisite compatibility. Some plugins may not be defined as multisite-compatible and yet can be used without breaking any features.

 

Cloning a site in a multisite installation

The Multisite feature gives us the ability to share the same installation and resources for multiple sites. However, it should only be used when you need a network with a large number of sites. In such scenarios, many of these sites may use the same theme and certain plugins, as well as certain settings. So, manually creating a site, installing the theme, installing plugins, and configuring settings becomes a tedious task for the administrator.

The cloning feature allows us to automatically create a new clone of an existing site, including all its configurations, within seconds. This will reduce the workload of the super administrator as well as avoid making mistakes with manual configurations.

In this recipe, we are going to look at the process of cloning a site in a multisite network using an existing WordPress plugin.

Getting ready

You need to create a site in-network or use the default site to add the necessary plugins, themes, settings, and data. Since we are going to clone a site, it's better to have as much test data as possible to understand how cloning works for plugins, themes, settings, media files, and so on.

You have to install the NS Cloner - Site Copier plugin to execute this recipe. To do so, follow these steps:

  1. Click the Plugins | Add New section.
  2. Search for NS Cloner - Site Copier in the Search plugins field.
  3. Once you see this plugin in the list of available plugins, click the Install Now button.
  4. Finally, click the Activate button to activate the plugin.

How to do it...

The NS Cloner plugin offers a built-in step by step process for creating a clone of a site. Follow these steps to clone one of the sites in your multisite network:

  1. Log in to the WordPress Dashboard as a super administrator.
  2. Click the NS Cloner menu item on the left menu.
  1. You will see the following screen. From here, you can configure the cloning process:

  1. Select Standard Clone for the Select Cloning Mode setting.
  2. Select the site you want to clone for the Select Source setting.
  3. Add a title and a unique URL for the site in the Create New Site section.
  4. Click the CLONE button at the bottom to clone the site.
  5. You will see the following screen, which shows the cloning process:

  1. Once cloning is completed, you will get another screen with the result of the cloning process:

Now, you should see a copy of the selected site in the Sites section of your multisite network.

How it works...

Once the Clone button has been clicked, the NS Cloner - Site Copier plugin updates the database by adding existing site data and settings. Since we are on a multisite network, the same plugins and themes are shared across all sites. So, the NS Cloner - Site Copier plugin doesn't need to copy the plugin or theme files.

 Also, the plugin will create a new directory in the wp-content/uploads/sites directory with the numeric ID of the new site. Then, it will copy all the media files from the existing site to the new site.

Finally, it will replace the necessary URLs of the existing site to those of the cloned site so that you can start working on it without manual configurations.

There's more...

The plugin allows us to log the cloning process into a file. In the cloning process, there is a section called Additional Settings. You have to select the Enable Logging option before clicking the Clone button. The cloning process will be the same as we explained earlier. Now, you can click on the NS Cloner | Logs / Status section to view the available log files. You can click on the View Log button for the specific cloning process. This will show a full list of activities in the cloning process and details of how cloning actually works. The following screenshot shows the log that was generated from cloning:

You can use this screen to understand what types of file and database operations are executed to clone the site. The line in the first highlighted section inserts values into the wp_sitemeta table to keep the data about the cloning process. The next highlighted section shows how the cloner adds a comments table to the queue. Queries are processed internally to create database tables and add data to them. After the database table and data have been added, the cloner updates the progress in the last highlighted section to display it on the frontend. The last line also shows how many records were copied from the source site table to the new site table. These are only a few examples of how we can check the progress. 

About the Author

  • Rakhitha Nimesh Ratnayake

    Rakhitha Nimesh Ratnayake is a freelance web developer, writer, and open source enthusiast. He has over 9 years of experience in developing WordPress applications and plugins. He develops premium WordPress plugins for individual clients and the CodeCanyon marketplace. User Profiles Made Easy and WP Private Content Pro are the most popular plugins developed by him. Building Impressive Presentations with impress.js was his first book, which was published by Packt Publishing. He is also the author of the first three editions of WordPress Web Application Development. In his spare time, he likes to read books and spend time with his family

    Browse publications by this author

Latest Reviews

(2 reviews total)
After working on WordPress sites for a couple of years, I was looking for an additional set of solutions to get more out of WordPress. Instead the book just covers basic concepts of WordPress, declared as receipies. So I get nearly no additional knowledge out of those aprox 650 pages. The book itself is not so bad, e.g. for beginners to dive in the word of WordPress. But the additional benefit for more experienced users is very much limited.
Good up to date content on a fast moving topic...