Book Image

WordPress Development Quick Start Guide

By : Rakhitha Nimesh Ratnayake
Book Image

WordPress Development Quick Start Guide

By: Rakhitha Nimesh Ratnayake

Overview of this book

WordPress is the most used CMS in the world and is the ideal way to share your knowledge with a large audience or build a profitable business. Getting started with WordPress development has often been a challenge for novice developers, and this book will help you find your way. This book explains the components used in WordPress development, when and where to use them, and why you should be using each component in specific scenarios. You begin by learning the basic development setup and coding standards of WordPress. Then you move into the most important aspects of the theme and plugin development process. Here you will also learn how themes and plugins fit into the website while learning about a range of techniques for extending themes and plugins. With the basics covered, we explore many of the APIs provided by WordPress and how we can leverage them to build rapid solutions. Next, we move on to look at the techniques for capturing, processing, and displaying user data when integrating third-party components into the site design. Finally, you will learn how to test and deploy your work with secure and maintainable code, while providing the best performance for end users.
Table of Contents (16 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Setting up the development environment


In order to get started with WordPress development, you will need a working development environment that supports WordPress. So, we need to focus on the essential steps for building a development environment, such as the following:

  • Installing a development stack that supports PHP, Apache, and MySQL or Maria DB
  • Installing and configuring WordPress
  • Setting up web browsers and code editors

Let's take a quick look at each of these options for building the ideal development environment for WordPress.

Installing the development stack

The most basic requirements for running WordPress include PHP, Apache server, and a MySQL database. So, we need to either install these components from scratch or use existing tools such as WAMP, XAMPP, or MAMP. Since this book is about a quick start to WordPress development, we are going to use existing tools without wasting time on manual installation. You can choose the tool depending on your operating system. For this book, we are going to use the WAMP server on the Windows platform.

The WAMP server offers a built-in installation process, and all you need is to provide the requested inputs while going through several well-defined installation screens. Since this is already discussed in several online resources, we are not going to explain the installation process here. You can refer to http://www.wampserver.com/en/ for instructions on setting up WAMP.

Installing and configuring WordPress

Once the development stack is installed, we can move to the WordPress installation process. WordPress offers one of the simplest automated processes for installing a software framework. The complete installation process takes no more than 5-6 steps and a few minutes. Since it's already documented comprehensively in the WordPress codex, we are not going to waste time explaining it from scratch. You can refer to https://codex.wordpress.org/Installing_WordPress#Detailed_Instructions for the complete installation process.

Even though installation is a simple process, configuration might vary based on your requirements as well as different environments. Therefore, we are going to discuss the configuration in detail in the upcoming sections.

Setting up web browsers and code editors

As a developer, you should already have at least two browsers installed on your system. WordPress is frequently updated with modern versions of libraries and trends, such as responsive design. So, you need to make sure that the available browsers are updated to the latest versions. Also, you may have to install all popular browsers such as Chrome, Firefox, Opera, Safari, and Internet Explorer to adhere to browser compatibility.

A code editor is another important aspect of development, where developers need to choose one that favors their personal interests. Some popular code editors include Sublime Text, Brackets, Textmate, and Notepad++. When choosing a code editor, you need to look for essential features, such as the following:

  • Supported programming languages
  • Syntax highlighting and code readability
  • Autocompletion
  • Simplified indentation and formatting
  • Version management
  • File/folder search and replacement

Many of these editors are fully featured solutions and hence all these features are available by default. In such cases, you can make the decision based on your personal preferences. At this point, our development environment is ready with the most common tools for getting started.

Preparing development tools

Even though we can start the development right away, it's important to have the necessary tools that make our tasks easier as developers, while saving precious time. You can find hundreds of developer tools created to test and debug the code and help you pinpoint the issues in your implementations. Here, we are going to look at some of the most essential tools to support your development.

Client-side monitoring with browser development tools

There was a time when we had to install different extensions to use development tools in different browsers. Now, development tools have become the norm in the latest versions of all modern browsers. These tools provide a wide range of facilities to debug your code. The following screenshot previews the developer tools section of the Chrome browser:

The preceding screenshot previews the Console tab, where you will see errors, notices, and information related to user requests. This tab simplifies the process of tracking and fixing errors in your client-side coding. We can also use other tabs such as Sources, Network, Performance, Security to track AJAX requests, file loading precedence, memory, and bandwidth usage, along with possible security risks.

"AJAX is a short term for Asynchronous JavaScript and XML. AJAX is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously (in the background) without interfering with the display and behavior of the existing page."

– Wikipedia

Other browsers provide built-in development tools with similar features. The Firefox browser consists of Inspector,Console, Debugger, Style Editor, Performance, Memory, Network, and Storage tabs. Internet Explorer consists of DOM Explorer, Console, Debugger, Network, UI Responsiveness, Profiler, and Memory tabs. The main feature set is consistent across all browsers. As a developer, you should use browser tools at least for simple tasks, such as monitoring errors, inspecting HTML tags, tracking AJAX requests, and testing CSS styles.

Server-side monitoring with WordPress plugins

The WordPress plugin repository provides quite a few plugins to help developers track errors, performance issues, styles used in requests, executed hooks, loaded scripts, and various kind of other useful features. It's up to you to choose the number of plugins to use, and which plugins to use. In this section, we are going to look at some of the most popular plugins for debugging and testing.

Query Monitor

This is the most widely used plugin among the recently updated plugins in the debug category. The primary functionality of this plugin is to monitor the database queries in user requests and help you optimize them. We use many plugins to build a WordPress site, and hence each user request may execute a large number of queries. In most scenarios, a considerable amount of queries are not relevant to the user request and executed due to low quality coding from plugin developers. This plugin allows you to track queries by plugin, making it easier to identify the plugins responsible for executing a large number of queries, as well as unnecessary ones.

The following screenshot previews the use of Query Monitor to track the queries executed by the WordPress core and individual plugins:

Apart from monitoring queries, you can also use this plugin to check hooks, scripts, and styles loaded in the current user request. Query Monitor is a must-use plugin for WordPress. You can find more details about Query Monitor plugin at https://wordpress.org/plugins/query-monitor/.

Debug This

This is one of the more recently created plugins to support developers. Unlike Query Monitor, this plugin doesn't have a primary feature. Instead, it offers a wide range of features for tracking all types of features in WordPress. You can track shortcodes, post types, PHP class/function usage, media attachments, and many other things, along with the features we already discussed in Query Monitor.

The following screenshot previews the use of Debug This with the list of available features:

As you may notice, this is an extremely useful tool for developers. The only drawback is the output of information as plain arrays, making it difficult to read. Even though it lacks the proper organization of information using user-friendly screens, you can resolve complex issues without using your own var_dump inside the code. You can find more details about the Debug This plugin at https://wordpress.org/plugins/debug-this/.

Apart from these two plugins, there are more useful plugins to help developers write quality code and save time with error handling and optimization. The following is a list of such plugins to be used in development:

We looked at most popular testing and debugging plugins in the WordPress plugin repository. There are premium plugins and online services for further improving the development process. You can test these plugins and see which ones fit into your development environment.

Working with the configuration file

WordPress uses a configuration file called wp-config.php, located inside the root directory of your WordPress installation. In the preceding section, we went through the installation process, and this file was generated automatically based on the specified information. In order to use the advanced features of WordPress, as well as making manual modifications based on system changes, we will explain this file thoroughly. Let's take a quick look at the initial contents of this file using the following code:

define('DB_NAME', 'wpquick'); 
define('DB_USER', 'wpdadmin'); 
define('DB_PASSWORD', ' GBm+Hq1T1Clyq '); 
define('DB_HOST', 'localhost'); 
define('DB_CHARSET', 'utf8mb4'); 
define('DB_COLLATE', ''); 
 
define('AUTH_KEY',         '}ezywl=_z-&_r-Ter]^)GafZQ!;T}sG{`RI?y.!BDgKKtW6WLqk>FnH<p1@ZsHZ`'); 
define('SECURE_AUTH_KEY',  'm1+,]G-])dt)%T:9ziw;|,]s&k^ ^Z0Vp.7DaSC0U)GT>*GY:jW@'); 
define('LOGGED_IN_KEY',    '&W_%WB%jjS0+_oBN:-cz5]qK<Jv*1{oM vji[~}k(uN*`g>wczC}<6?8t!BX{Z;G'); 
define('NONCE_KEY',       'vL9gM*pJPP3BC>I29+8*f[[)%kI$>)^clg%T;`9ONsl7RXAkzm]oX18Y~1c.;n%6'); 
define('AUTH_SALT',        'y>:&&$GBm+Hq1T1Clyq=Vp{Mk>f;nRofa/f!i}ex(m&-rs&dkT!ja0ilwJD~Lk4qQ'); 
define('SECURE_AUTH_SALT', 'PQMwuucwM`=0z7AwEJO@## }kQ]+o,bl2CZ()!d|*_FEl)>iI'); 
define('LOGGED_IN_SALT',   'XDlT]5pBg4jTg=e#XA2u{CTrdP!SU|aD o&Rq4/}: !Gu_2;)u-nW}0(/EEu4Ysb'); 
define('NONCE_SALT',       'CCX2?iAcCJ{Se5!ViEUO(/E0~/`ez_TZ=oAFrZ?DMru/RzLz(iPv(LwV%L0#a5px'); 
 
$table_prefix  = 'wp_'; 
define('WP_DEBUG', false); 
 
if ( !defined('ABSPATH') ) 
   define('ABSPATH', dirname(__FILE__) . '/'); 
require_once(ABSPATH . 'wp-settings.php'); 

The first section of the file handles database configurations for your site. As you can see, database details are already added based on the inputs you provided in the installation process. You need to modify this section manually when you move the site from a local environment to a live environment, or when you make changes in database details such as username and password. Once database details are modified and saved, it will immediately impact the loading of your site.

The next section defines the WordPress security keys. These keys are automatically generated on WordPress installation. In scenarios where you don't have the security keys, you can go to https://api.wordpress.org/secret-key/1.1/salt/ and generate a new set of keys. This section consists of four keys and four salts for your website. These keys are used to secure the cookies for your users. You don't have to know the meaning of each key or remember the keys. WordPress will use these keys to generate hash values of cookie names as well as cookie values, making it difficult to hack your authentication details. No matter how many security precautions we take, there is a chance of your site getting hacked due to the open source nature of WordPress and use of third-party plugins. In such situations, you can regenerate and add these keys to the config file. This will invalidate all existing cookies and hence all users will have to log in again.

The next two lines define the table prefix and the debug mode. The prefix is configured by the input you provide in the installation process. It's recommended to change the prefix to anything other than wp, to improve security. By default, the debug mode is set to FALSE and hence you won't see any PHP errors on your site. In a development environment, you should change this value to TRUE, in order to identify the errors in code. Once development is completed, you should change it back to FALSE before uploading the file to a live server. The final few lines define the file path, and load the settings file.

This is the most basic version of the wp-config.php file, and it's adequate for handling basic WordPress sites.

An overview of advanced configurations

As a developer, you will have to build from simple WordPress blogs to fully functional web applications. So, advanced configurations become important for security, advanced features, and the performance of applications. Let's take a quick look at how you can modify the configuration file using other configuration options.

Securing plugins and upload directories

Due to the open source nature of WordPress, everyone knows where plugins and files are stored in your site. Therefore, the process of hacking or spamming your site becomes easier for potential attackers. As a solution, we can move plugin and upload directories to a different path using the config file, to increase the difficulty of finding paths to attack.

Let's add more configurations to change the default location of these directories:

define( 'WP_PLUGIN_DIR', $_SERVER['DOCUMENT_ROOT'] . '/example.com/modules/' ); 
define( 'WP_PLUGIN_URL', 'http://localhost/ example.com /modules/'); 
define( 'UPLOADS', 'modules/media' ); 

The first two lines move the plugin directory from wp-content/plugins to the modules directory in your root directory. Since the path has changed to the root directory, it will be difficult for attackers to identify the path. These configurations only change the directory. If you already have plugins in the wp-content/plugins directory, you will have to move them manually to a new directory. The next line changes the media upload path from wp-content/uploads to the modules/media directory inside the main installation.

The process of moving the theme directory is not straightforward as the path is configured relative to the wp-content directory. Therefore, you will have to change the main path of the wp-content directory in situations where you want to change the theme directory. You may use these configurations manually, or use existing plugins to help secure your site.

Configuring advanced debugging settings

Earlier, we enabled debugging in the development environment by setting WP_Debug to TRUE. There are more settings to control the debugging process and provide more information on issues in our code. Let's walk through some of the advanced options for developers.

Script debugging

In general, conflicts in JavaScript files are a common problem due to the use of different script versions in different plugins and themes. Identifying these errors is a cumbersome process when using minified versions and concatenated script files. Let's take a look at some of the rules used for resolving these issues:

define( 'SCRIPT_DEBUG', true ); 
define( 'CONCATENATE_SCRIPTS', false ); 

The first line enables script debugging by loading the uncompressed file instead of the minified version. The second line prevents concatenation of multiple scripts, allowing you to track the line of the error. You should use these configuration rules when you are experiencing script issues in WordPress core files.

Logging errors and customizing php.ini rules

We can either display the coding errors in the browser or log them to a separate log file. It's at the preference of the developer, but I think logging the errors is the ideal solution for future reference. Also, sometimes we need to change the PHP configurations to make our code work. Many hosting servers will not allow you to directly edit the php.ini file, and hence we can use the wp-config.php file to override the default settings of the php.ini file.

Note

Some hosting providers don't provide access to change the php.ini file, and you will have to request modification through server support.

Consider the following configuration rules for error logging with php.ini modifications:

@ini_set( 'log_errors', 'On' ); 
@ini_set( 'display_errors', 'Off' ); 
@ini_set( 'error_log', '/home/example.com/logs/php_error.log' ); 

First, we enable error logging in PHP and disable displaying errors in the browser by using the display_errors setting. Then, we define the path of the file where errors will be logged. You need to create this directory first and provide the necessary write permissions before this rule takes effect.

In this section, we had a brief overview of some of the most basic and advanced configurations in WordPress development. There are many other settings to help developers, as well as control features. You can take a look at the available configurations and their use in the WordPress codex at https://codex.wordpress.org/Editing_wp-config.php. Now, we have the complete setup to begin development tasks on top of WordPress.