Home Web Development WordPress Development Quick Start Guide

WordPress Development Quick Start Guide

By Rakhitha Nimesh Ratnayake
books-svg-icon Book
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $29.99 $20.98
Print $38.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Introduction to WordPress Development
About 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.
Publication date:
October 2018
Publisher
Packt
Pages
300
ISBN
9781789342871

 

Chapter 1. Introduction to WordPress Development

WordPress is the most widely-used CMS in the world, and the demand for developers is on the rise. Beginner WordPress developers are often restricted to using existing plugins and making minor modifications with the theme functions file. As a developer, you need a thorough understanding of WordPress core modules and components, along with a proper development setup to tackle complex application requirements.

This chapter focuses on introducing you to the prerequisites of WordPress development while clearing up some of the misconceptions about development. Unlike other frameworks, WordPress doesn't have an MVC architecture or similar. So, developers have the freedom to find their own techniques. We will begin by having a high-level overview of how developers can use the existing features in development, as well as the techniques for integrating our code with WordPress components. Then, we will move on to installing WordPress and discussing the use of configuration files with default and advanced configurations. Development tools and coding standards are the keys for producing quality code, and hence we will discuss the use of WordPress-specific coding standards as well as the use of popular open source development tools.

In this chapter, we will cover the following topics:

  • Installing and configuring a development environment for WordPress
  • How to use a WordPress configuration file
  • A high-level overview of the WordPress file/directory structure and their use in development
  • A brief introduction to WordPress coding standards and its usage
  • Using popular tools for debugging code

By the end of this chapter, you will have the necessary knowledge to understand the key development areas of WordPress and preparing the development environment for a smooth workflow.

 

Introduction to WordPress development


This book is intended for beginner WordPress developers and site owners who want to build custom websites with WordPress. We dive into developing solutions with WordPress, it's important to understand what exactly development is, and the areas involved. There are many people who call themselves WordPress developers and yet haven't done anything beyond changing some theme designs and using the theme functions file. WordPress development can range from simple theme design changes to building a complex web application.

Here are the components involved in WordPress development:

  • Theme functions file: The first technique you encounter when getting started with development. Usually, we can add small code snippets using filters and actions to change the functionality of theme or plugins. Since this file is updated on theme updates, it's not recommended to add your own custom code. However, there are exceptions when using your own theme or a theme without version updates. This is a good starting point to add some code and learn how WordPress can be customized with actions and filters.
  • Child themes: This is the next step in development, before diving into complex implementations using plugins. The child theme is a theme that we create based on an existing theme. We can either override all files in the child theme or only add the necessary files to override. If you are starting WordPress development and want to add some quick code snippets, creating a child theme and using the functions file is the ideal solution. In development, the child theme should be used for minor implementations such as design changes or displaying more/less data on frontend screens. Since we only use the functions.php file for code changes, this technique is not recommended for implementing advanced features. However, modern themes are packed with features and hence there may be exceptions for doing advanced implementations in child themes.
  • Plugins: As a developer, developing plugins is the most important aspect of building custom websites. Plugins allow you to build independent and extendable solutions. Usually, it's a good practice to add any customization into a separate plugin or a site-specific common plugin based on its scope. You can create plugins to customize existing WordPress backend and frontend features, theme functionality, as well as developing completely new features beyond WordPress's built-in modules.
  • Addons: Even though we call these addons, they are a plugin that extends the features of another plugin. In WordPress development, we are not going to build everything from scratch as there is a huge free plugin repository and thousands of premium plugins for doing all kinds of things. Most of these existing plugins are not going to align perfectly to our requirements. Therefore, we need a way to customize the features of such plugins without losing the changes on plugin updates. Addons extend the features of plugins by using actions, filters, and APIs provided by the plugin.

These are the main components and files for developing your own solutions in WordPress. Now, we need to shift focus to major areas involved in development and how they fit into WordPress. Let's review the use of existing features in development as well as custom build features.

Posts, pages, and custom post type management

Since its inception, WordPress was used as a basic CMS with the primary focus on blogging. After so many years, posts and pages are still the main aspect of WordPress, with the addition of custom post types. The primary feature of many sites is the management of posts. So, you need to master each and every aspect of post creation, editing, displaying, and managing additional data. With the arrival of custom post types, developers can match many of the user data capturing application requirements. Since the basic features such as creating, editing, displaying, and listing are inbuilt with custom post types, developers can focus on extending these features at a rapid pace.

Many large-scale applications such as event management systems, online shops, realestate sites, and job management sites are modeled using custom post types, and hence it's a primary feature in WordPress development.

User management

This is another built-in module with comprehensive functionality for user data, access levels, and permissions. You may find the need for registered members in many modern applications and sites. So, you can use the features of existing user modules to handle basic user data and permissions, while developing advanced features such as frontend login, registration, and profile management with the extension of core features.

Similar to custom post types, you will find many applications with one of the primary features as user management. Forums, online student management systems, and CRMs are some of the examples of high-level user management applications with WordPress.

Form data management

The process of capturing, processing, and displaying user data is the primary feature of many websites. We already discussed the use of custom post types for simplifying the data modeling process. However, inbuilt custom post type features are only available in the backend. Form management is essential for capturing the user data to the custom post types from the frontend. There are certain limitations that force us to use form management from scratch without using custom post types on some occasions. Such limitations include the use of existing database tables, hooks, and built-in templates in custom post types.

We can add forms using theme templates, shortcodes, or existing hooks. Modern JavaScript libraries will be used to process them while using custom database tables to enhance flexibility. So, this is another essential skill in WordPress development.

Building custom layouts and extending theme layouts

Each WordPress site or application is built around a theme and set of plugins. In general, most people prefer to use a high-quality existing theme, while some of them require a complete theme built for them from scratch. Regardless of these preferences, you need to be skilled in theme development, in order to cater to modern trends. Widget-based dynamic screens, responsive layouts, and dynamic content displays based on user preferences are some of the modern trends used in themes. The most common form of development is the customization of existing theme layouts and building new post/page templates.

Modern applications may also require you to add complex features into the theme instead of separating them into plugins. So, you need to have hands-on experience in theme files as well as common theme hooks for building advanced user interfaces.

These are some of the frequently involved areas in WordPress development, and hence you need to be familiar in order to deliver rapid solutions. Apart from these areas, you can extend most WordPress features using existing hooks, as well as build custom features such as APIs, integration of third-party UI components, and so on.

 

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.

 

Understanding the role of the WordPress file and directory structure


Beginning WordPress development is not a complex task. It's about making minor theme changes, installing and customizing existing plugins, and using the available hooks. As you move on, complex requirements come your way with the expectation of future-proof solutions. Trying to build such solutions without considering future WordPress, plugin, and theme versions can lead to a nightmare. Getting used to existing WordPress files/directories and knowing their role is vital in developing maintainable solutions. In this section, we are going to look at the existing files and directories of a default WordPress installation.

The following is a screenshot of typical files and directories inside your WordPress installation:

Let's look at some of the most important files and directories inside WordPress:

  • wp-admin: This is where WordPress stores files related to admin-side functionality. The files in this directory are based around the admin.php file. Primary functionalities of these files include checking admin permission, connecting to the database, and loading the admin dashboard features. This directory is upgraded with WordPress version updates and hence the content of these files is replaced.
  • wp-content: This is where WordPress stores user-uploaded files such as plugins, themes, and media files. We can add additional files/directories here without being affected by WordPress version updates. So, the content in this directory will not be replaced.
  • wp-includes: This is the largest directory in WordPress with over 800 files to power the features of the admin dashboard as well as frontend functionality. The primary file in this directory is functions.php, considered as the main WordPress API. This directory is upgraded with WordPress version updates and hence the content of these files is  replaced.
  • .htaccess: This file is where you describe configuration rules for your Apache server. By default, it will contain minimal rules. You can manually add configuration rules based on your requirements. There are plugins that automatically add the necessary configuration rules to this file. This file is used for the configuration of WordPress permalinks. Changing the permalink structure from the WordPress settings section is the simplest way to track rule changes in this file.
  • index.php: This file is responsible for initializing WordPress based on user requests, and serving the response.
  • wp-config.php: This file is used for all the configurations for your site including databases, secret keys, plugins, and theme directory paths. So, it's very important to keep this file as secure as possible. This file is not replaced on WordPress version upgrades and hence you can use your own configurations.

Here, we looked at the most important files and directories involved in development. You can also check the comments of other core files to understand their functionality.

How to choose files and directories for development

The process of WordPress development is slightly more challenging compared to other PHP frameworks. With any other framework, we choose a specific framework version and develop the features for that specific version. It's entirely optional to upgrade our solution's future versions of the framework. However, it's the opposite with WordPress. We can't stick with a specific WordPress version for a long time, especially due to security concerns. Most of you will want to upgrade the version as soon as WordPress releases a new version. Therefore, it's important to develop solutions that don't break with version upgrades. Basically, we should be able to upgrade WordPress without touching any of our code.

So, the first thing you need to understand is where you can place your code files and how you can use the core WordPress files/directories in development. We discussed the main files and directories inside the WordPress directory in the previous section. Let's narrow it down to the files and folders used for custom development. Basically, we have to choose files and folders that are not replaced by WordPress updates. Among the files and folders we discussed, wp-content, wp-config.php, and htaccess are not affected by upgrades. So, our development should focus on these files and folders.

As we mentioned, wp-content is the directory where all the user-uploaded files are stored. So, we need to add our code files inside this directory. Let's explore the contents of this directory to understand where and what kinds of files can be created.

The following is a screenshot of files and folders inside your wp-content folder:

The preceding screenshot contains both default directories and custom directories created based on custom requirements. Let's have a brief overview of the role of each folder:

  • plugins: This is where WordPress stores all the plugins required to run your site. You will get Akismet Anti-Spam and Hello Dolly plugins on initial installation. Afterwards, you can use this directory to add your own plugins as well as install existing plugins from other developers. This directory can be considered as the heart of WordPress development.
  • themes: This is where WordPress stores all your themes that power the design and initial functionality of your site. Initial installation contains a few default themes such as Twenty Seventeen, Twenty Sixteen, and so on. Afterwards, you can use this directory to add your own themes as well as install existing themes from other developers. Unlike plugins, you can only use one theme from this directory at any given time.
  • uploads: This is where all the user-uploaded files for posts, pages, and plugins will be stored. This directory is not created until you upload the first file. Usually, all the media files for posts and pages will be stored with a sub-directory structure of year/month format. You can create unlimited sub-directories to handle files for plugins and themes.
  • languages: This directory is not available on initial installation and is created when you change the language in WordPress. So, it's not important for the development tasks.
  • mu-plugins: This directory stores must-use plugins for your site and is not available on initial installation. A must-use plugin is a plugin that's mandatory to run the site and hence it's not possible to deactivate. These plugins are automatically enabled on all sites of your WordPress installation. Even though these plugins are useful in some scenarios, it's not ideal to use them due to some of the limitations in executing certain hooks. So, we are not considering them for the development tasks of this book.
  • upgrade: This directory is not available by default and is used for storing temporary files for WordPress version upgrades. So, it's important for our development tasks.
  • cache and logs: These are some of the custom directories created by plugins or themes to handle certain features. I have used them in this screenshot to explain the use of custom folders. You can create such custom folders to handle files related to themes or plugins.

After having a quick overview of files and directories, we can come to the conclusion that our primary focus should be on the plugins, themes, and uploads directories inside the wp-content directory. Using code and media files in these directories ensures our solutions are not wiped out by version upgrades.

 

A brief overview of WordPress coding standards


In programming, writing working code is not the only responsibility of the developers. They are responsible for writing quality code that is extendable for future enhancements, as well as making sure the code is easily understandable for other developers. This is where coding standards become an important aspect of development. Coding standards are a set of rules and conventions specific to a programming language, and all developers are expected to follow them to make the code consistent.

I assume that you are familiar with PHP coding standards and ready to develop WordPress with that experience. However, WordPress itself has a set of coding standards and some of these rules are slightly different to PHP standards. The coding standards are currently divided into four sections, called PHP, HTML, CSS, and JavaScript. As a developer, you need to be familiar with WordPress coding standards, especially when you are developing themes and plugins for the WordPress repository.

Let's take a look at some of the main PHP coding standards used in WordPress:

  • Single quotes and double quotesPHP processes single quotes quicker than double quotes since the parser doesn't have to detect and execute any variables. That's why it's better to use single quotes for strings that don't have any evaluations.
  • Indentation: You should use tabs instead of spaces for indenting the code.
  • Opening and closing brackets: You should always use opening and closing brackets even when it's not necessary for single line evaluations.
  • Using spaces: WordPress recommends putting spaces after commas, and on both sides of logical, comparison, string, and assignment operators.
  • Naming conventions: You should always use lowercase letters and underscores for naming variables, functions, actions, filters, and so on. The camelCase method is not recommended in WordPress coding standards.
  • Dynamic hooks: Hooks are unique to WordPress and hence the guidelines suggest using interpolation by wrapping the variable in curly brackets, instead of using concatenation.

These are some of the common coding standards for WordPress, and you can find the complete set of standards, including CSS, JavaScript, and HTML, at https://codex.wordpress.org/WordPress_Coding_Standards. Those developers who are familiar with pure PHP coding will notice the slight changes in WordPress standards, such as using lots of spaces and not using camel case for functions. So, it's a challenge even for experienced developers to come out of your comfort zone and write code the WordPress way.

The preceding section illustrated the main PHP coding standards. Most of you should have a general idea of these standards, as you have already worked with PHP. However, there are WordPress-specific coding styles/conventions due to hook-based architecture. Many of you may not be aware of these conventions, which are essential for building themes and plugins that don't conflict with others.

Let's have a quick overview of some of these conventions, which will be discussed in detail throughout the book:

  • Loading scripts and styles: Usually, we can load scripts and styles anywhere in an HTML page by using <script> and <link> tags. WordPress uses built-in PHP functions to load scripts and styles. Therefore, it's recommended that you load these files only within an action called wp_enqueue_scripts. Loading these files outside this action could result in conflicts with WordPress core features as well as other plugins or themes.
  • Loading third-party libraries: Libraries such as jQuery, Underscore, and Backbone.js are used frequently in modern web development. Usually, developers have the option to include these libraries within their code files or load them from a CDN for faster performance. This technique is not feasible in WordPress as many plugins from different developers are involved. Therefore, we need to load one common version of the library to avoid conflicts in code. So, we have to use the library version that comes built-in with WordPress.
  • Using proper events for execution: In pure PHP programming, we can execute code anywhere and anytime based on our preferences. WordPress uses an event-driven architecture with hooks, and hence code is executed through events in a predefined manner. Unless we use the correct events, our code is going to conflict with code from other. For example, we need to access $_POST variables within or after an init hook. Trying to access this data before the necessary event could lead to errors in your code.

We had a brief introduction to the coding standards and conventions needed to get started with WordPress development. Often, you will find it sufficient for development projects for specific clients. However, you will sometimes need further knowledge, especially on event-based conventions for plugin and theme development. We will cover the necessary coding conventions throughout the upcoming chapters.

 

Summary


The goal of this chapter was to get the environment ready and understand the prerequisites for complex development tasks. We explored the techniques for integrating our code into WordPress, as well as identifying the most used modules in development.

We had a brief overview of the installation and configuration of the development environment, while identifying the necessary tools for simplifying our tasks. Finally, we went through the WordPress file and directory structure to understand how our solutions can be provided in a future-proof manner.

In Chapter 2, Managing Database Structure, Storage, and Retrieval, we will be exploring the existing WordPress database structure and its use, while discussing the practical uses of custom database tables.

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 (3 reviews total)
I'd give it 5 stars because it is a clear and detailed guide, but I only give 4 due to my expectations: I'd preferred a guide which allowed you to go to the section you need to use, and with backward and forward references pointing other things you need to learn before start working. This one is made to be read from start to end. If you'd need to develop a plugin with only admin side, you will have to read all about plugin development to get what you need.
The book is understandable and really is a good start for Wordpress development.
Nice content but the epub needs better formatting
WordPress Development Quick Start Guide
Unlock this book and the full library FREE for 7 days
Start now