Home Web Development WordPress Web Application Development

WordPress Web Application Development

By Rakhitha Nimesh Ratnayake
books-svg-icon Book
eBook $43.99 $29.99
Print $54.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 $43.99 $29.99
Print $54.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
    WordPress as a Web Application Framework
About this book
Publication date:
May 2015
Publisher
Packt
Pages
404
ISBN
9781782174394

 

Chapter 1. WordPress as a Web Application Framework

In recent years, WordPress has matured from the most popular blogging platform to the most popular content management system. Thousands of developers around the world are making a living from WordPress design and development. As more and more people are interested in using WordPress, there are discussions and arguments about exploring the possibilities of using this amazing framework for web application development.

The future seems bright as WordPress has already got dozens of built-in features, which can be easily adapted to web application development using slight modifications. Since you are already reading this book, you have to be someone who is really excited to see how WordPress fits into web application development. Throughout this book, we will learn how we can inject the best practices of web development into WordPress framework to build web applications in rapid process.

Basically, this book will be important for developers from two different perspectives. On one hand, beginner- to intermediate-level WordPress developers can get knowledge of cutting-edge web development technologies and techniques to build complex applications. On the other hand, web development experts who are already familiar with popular PHP frameworks can learn WordPress for rapid application development. So, let's get started!

In this chapter, we will cover the following topics:

  • WordPress as a CMS

  • WordPress as a web application framework

  • Simplifying development with built-in features

  • Identifying the components of WordPress

  • Making a development plan for portfolio management application

  • Understanding limitations and sticking with guidelines

  • Building a question-answer interface

In order to work with this book, you should be familiar with WordPress themes, plugins, and its overall process. Developers who are experienced in PHP frameworks can work with this book while using the reference sources to learn WordPress. By the end of this chapter, you will have the ability to make the decision to choose WordPress for web development.

 

WordPress as a CMS


Way back in 2003, WordPress released its first version as a simple blogging platform and continued to improve until it became the most popular blogging tool. Later, it continued to improve as a CMS and now has a reputation for being the most popular CMS. These days everyone sees WordPress as a CMS rather than just a blogging tool.

Now the question is, where will it go next?

Recent versions of WordPress have included popular web development libraries such as Backbone.js and Underscore.js and developers are building different types of applications with WordPress. So, we can assume that it's moving in the direction of building applications. It's important to keep an eye on the next few versions to see what WordPress offers for web applications.

Before we consider the application development aspects of WordPress, it's ideal to figure out the reasons for it being such a popular framework. The following are some of the reasons behind the success of WordPress as a CMS:

  • Plugin-based architecture for adding independent features and the existence of over 20,000 open source plugins

  • A super simple and easy-to-access administration interface

  • A fast learning curve and comprehensive documentation for beginners

  • A rapid development process involving themes and plugins

  • An active development community with awesome support

  • Flexibility in building websites with its themes, plugins, widgets, and hooks

These reasons prove why WordPress is the top CMS for website development. However, experienced developers who work with full stack web applications don't believe that WordPress has a future in web application development. While it's up for debate, we'll see what WordPress has to offer for web development.

Once you complete reading this book, you will be able to decide whether WordPress has a future in web applications. I have been working with full stack frameworks for several years, and I certainly believe the future of WordPress for web development.

 

WordPress as a web application framework


In practice, the decision to choose a development framework depends on the complexity of your application. Developers will tend to go for frameworks in most scenarios. It's important to figure out why we go with frameworks for web development. Here's a list of possible reasons why frameworks become a priority in web application development:

  • Frameworks provide stable foundations for building custom functionalities

  • Usually, stable frameworks have a large development community with an active support

  • They have built-in features to address the common aspects of application development, such as routing, language support, form validation, user management, and more

  • They have a large amount of utility functions to address repetitive tasks

Full stack development frameworks such as Zend, CodeIgniter, and CakePHP adhere to the points mentioned in the preceding section, which in turn becomes the framework of choice for most developers. However, we have to keep in mind that WordPress is an application where we built applications on top of existing features. On the other hand, traditional frameworks are foundations used for building applications such as WordPress. Now, let's take a look at how WordPress fits into the boots of web application framework.

The MVC versus event-driven architecture

A vast majority of web development frameworks are built to work with MVC architecture, where an application is separated into independent layers called models, views, and controllers. In MVC, we have a clear understanding of what goes where and when each of the layers will be integrated in the process.

So, the first thing most developers will look at is the availability of MVC in WordPress. Unfortunately, WordPress is not built on top of the MVC architecture. This is one of the main reasons why developers refuse to choose it as a development framework. Even though it is not MVC, we can create custom execution process to make it work like a MVC application. Also, we can find frameworks such as WP MVC, which can be used to take advantage of both WordPress's native functionality and a vast plugin library and all of the many advantages of an MVC framework. Unlike other frameworks, it won't have the full capabilities of MVC. However, unavailability of the MVC architecture doesn't mean that we cannot develop quality applications with WordPress. There are many other ways to separate concerns in WordPress applications.

WordPress on the other hand, relies on a procedural event-driven architecture with its action hooks and filters system. Once a user makes a request, these actions will get executed in a certain order to provide the response to the user. You can find the complete execution procedure at http://codex.wordpress.org/Plugin_API/Action_Reference.

In the event-driven architecture, both model and controller code gets scattered throughout the theme and plugin files. In the upcoming chapters, we will look at how we can separate these concerns with the event-driven architecture, in order to develop maintainable applications.

 

Simplifying development with built-in features


As we discussed in the previous section, the quality of framework depends on its core features. The better the quality of the core, the better it will be for developing quality and maintainable applications. It's surprising to see the availability of number of WordPress features directly related to web development, even though it is meant to create websites.

Let's get a brief introduction about the WordPress core features to see how it fits into web application development.

User management

Built-in user management features are quite advanced in order to cater to the most common requirements of any web application. Its user roles and capability handling makes it much easier to control the access to specific areas of your application. We can separate users into multiple levels using roles and then use capabilities to define the permitted functionality for each user level. Most full stack frameworks don't have a built-in user management features, and hence, this can be considered as an advantage of using WordPress.

Media management

File uploading and managing is a common and time consuming task in web applications. Media uploader, which comes built-in with WordPress, can be effectively used to automate the file-related tasks without writing much source code. A super-simple interface makes it so easy for application users to handle file-related tasks.

Template management

WordPress offers a simple template management system for its themes. It is not as complex or fully featured as a typical template engine. However, it offers a wide range of capabilities in CMS development perspective, which we can extend to suit web applications.

Database management

In most scenarios, we will be using the existing database table structure for our application development. WordPress database management functionalities offer a quick and easy way of working with existing tables with its own style of functions. Unlike other frameworks, WordPress provides a built-in database structure, and hence most of the functionalities can be used to directly work with these tables without writing custom SQL queries.

Routing

Comprehensive support for routing is provided through permalinks. WordPress makes it simple to change the default routing and choose your own routing, in order to built search engine friendly URLs.

XMR-RPC API

Building an API is essential for allowing third-party access to our application. WordPress provides built-in API for accessing CMS-related functionality through its XML-RPC interface. Also, developers are allowed to create custom API functions through plugins, making it highly flexible for complex applications.

Caching

Caching in WordPress can be categorized into two sections called persistent and nonpersistent cache. Nonpersistent caching is provided by WordPress cache object while persistent caching is provided through its Transient API. Caching techniques in WordPress is a simple compared to other frameworks, but it's powerful enough to cater to complex web applications.

Scheduling

As developers, you might have worked with cron jobs for executing certain tasks at specified intervals. WordPress offers same scheduling functionality through built-in functions, similar to a cron job. However, WordPress cron execution is slightly different from normal cron jobs. In WordPress, cron won't be executed unless someone visits the site. Typically, it's used for scheduling future posts. However, it can be extended to cater complex scheduling functionality.

Plugins and widgets

The power of WordPress comes from its plugin mechanism, which allows us to dynamically add or remove functionality without interrupting other parts of the application. Widgets can be considered as a part of the plugin architecture and will be discussed in detail further in this chapter.

Themes

The design of a WordPress site comes through the theme. This site offers many built-in template files to cater to the default functionality. Themes can be easily extended for custom functionality. Also, the design of the site can be changed instantly by switching compatible theme.

Actions and filters

Actions and filters are part of the WordPress hook system. Actions are events that occur during a request. We can use WordPress actions to execute certain functionalities after a specific event is completed. On the other hand, filters are functions that are used to filter, modify, and return the data. Flexibility is one of the key reasons for the higher popularity of WordPress, compared to other CMS. WordPress has its own way of extending functionality of custom features as well as core features through actions and filters. These actions and filters allow the developers to build advanced applications and plugins, which can be easily extended with minor code changes. As a WordPress developer, it's a must to know the perfect use of these actions and filters in order to build highly flexible systems.

The admin dashboard

WordPress offers a fully featured backend for administrators as well as normal users. These interfaces can be easily customized to adapt to custom applications. All the application-related lists, settings, and data can be handled through the admin section.

The overall collection of features provided by WordPress can be effectively used to match the core functionalities provided by full stack PHP frameworks.

 

Identifying the components of WordPress


WordPress comes up with a set of prebuilt components, which are intended to provide different features and functionality for an application. A flexible theme and powerful admin features act as the core of WordPress websites, while plugins and widgets extend the core with application-specific features. As a CMS, we all have a pretty good understanding of how these components fit into a WordPress website.

Here our goal is to develop web applications with WordPress, and hence it is important to identify the functionality of these components in the perspective of web applications. So, we will look at each of the following components, how they fit into web applications, and how we can take advantage of them to create flexible applications through a rapid development process:

  • The role of WordPress themes

  • The role of admin dashboard

  • The role of plugins

  • The role of widgets

The role of WordPress themes

Most of us are used to seeing WordPress as a CMS. In its default view, a theme is a collection of files used to skin your web application layouts. In web applications, it's recommended to separate different components into layers such as models, views, and controllers. WordPress doesn't adhere to the MVC architecture. However, we can easily visualize themes or templates as the presentation layer of WordPress.

In simple terms, views should contain the HTML needed to generate the layout and all the data it needs, should be passed to the views. WordPress is built to create content management systems, and hence, it doesn't focus on separating views from its business logic. Themes contain views, also known as template files, as a mix of both HTML code and PHP logic. As web application developers, we need to alter the behavior of existing themes, in order to limit the logic inside templates and use plugins to parse the necessary model data to views.

Structure of a WordPress page layout

Typically, posts or pages created in WordPress consist of five common sections. Most of these components will be common across all the pages in the website. In web applications, we also separate the common layout content into separate views to be included inside other views. It's important for us to focus on how we can adapt the layout into web application-specific structure. Let's visualize the common layout of WordPress using the following screen:

Having looked at the structure, it's obvious that header, footer, and the content area are mandatory even for web applications. However, the footer and comments section will play a less important role in web applications, compared to web pages. Sidebar is important in web applications, even though it won't be used with the same meaning. It can be quite useful as a dynamic widget area.

Customizing the application layout

Web applications can be categorized as projects and products. A project is something we develop targeting specific requirements of a client. On the other hand, a product is an application created based on the common set of requirements for wide range of users. Therefore, customizations will be required on layouts of your product based on different clients.

WordPress themes make it simple to customize the layout and features using child themes. We can make the necessary modifications in the child theme while keeping the core layout in the parent theme. This will prevent any code duplications in customizing layouts. Also, the ability to switch themes is a powerful feature that eases the layout customization.

The role of the admin dashboard

The administration interface of an application plays one of the most important roles behind the scenes. WordPress offers one of the most powerful and easy-to-access admin areas amongst other competitive frameworks. Most of you should be familiar with using admin area for CMS functionalities. However, we will have to understand how each component in the admin area suits the development of web applications.

The admin dashboard

Dashboard is the location where all the users get redirected, once logged into admin area. Usually, it contains dynamic widget areas with the most important data of your application. Dashboard can play a major role in web applications, compared to blogging or CMS functionality. The dashboard contains a set of default widgets that are mainly focused on main WordPress features such as posts, pages, and comments. In web applications, we can remove the existing widgets related to CMS and add application-specific widgets to create a powerful dashboard. WordPress offers a well-defined API to create a custom admin dashboard widgets and hence we can create a very powerful dashboard using custom widgets for custom requirements in web applications.

Posts and pages

Posts in WordPress are built for creating content such as articles and tutorials. In web applications, posts will be the most important section to create different types of data. Often, we will choose custom post types instead of normal posts for building advanced data creation sections. On the other hand, pages are typically used to provide static content of the site. Usually, we have static pages such as About Us, Contact Us, Services, and so on.

Users

User management is a must use section for any kind of web application. User roles, capabilities and profiles will be managed in this section by the authorized users.

Appearance

Themes and application configurations will be managed in this section. Widgets and theme options will be the important sections related to web applications. Generally, widgets are used in sidebars of WordPress sites to display information such as recent members, comments, posts, and so on. However, in web applications, widgets can play a much bigger role as we can use widgets to split main template into multiple sections. Also, these types of widgetized areas become handy in applications where majority of features are implemented with AJAX.

The theme options panel can be used as the general settings panel of web applications where we define the settings related to templates and generic site-specific configurations.

Settings

This section involves general application settings. Most of the prebuilt items in this section are suited for blogs and websites. We can customize this section to add new configuration areas related to our plugins, used in web application development.

There are some other sections such as links, pages, and comments, which will not be used frequently in complex web application development. The ability to add new sections is one of the key reasons for its flexibility.

The role of plugins

In normal circumstances, WordPress developers use functions that involve application logic scattered across theme files and plugins. Even some of the developers change the core files of WordPress, which is considered a very bad practice. In web applications, we need to be much more organized.

In the Role of WordPress theme section, we discussed the purpose of having a theme for web applications. Plugins will be and should be used to provide the main logic and content of your application. The plugins architecture is a powerful way to add or remove features without affecting the core. Also, we have the ability to separate independent modules into their own plugins, making it easier to maintain. On top of this, plugins have the ability to extend other plugins.

The role of widgets

The official documentation of WordPress refers to widgets as a component that adds content and features to your sidebar. In a typical blogging or CMS user's perspective, it's a completely valid statement. Actually, the widgets offer more in web applications by going beyond the content that populates sidebars. The following screenshot shows a typical widgetized sidebar of a website:

We can use dynamic widgetized areas to include complex components as widgets, making it easy to add or remove features without changing source code. The following screenshot shows a sample dynamic widgetized area. We can use the same technique for developing applications with WordPress.

Throughout these sections, we covered the main components of WordPress and how they fit into the actual web application development. Now, we have a good understanding of the components in order to plan our application developed throughout this book.

 

A development plan for the portfolio management application


Typically, a WordPress book consists of several chapters, each of them containing different practical examples to suit each section. In this book, our main goal is to learn how we can build full stack web applications using built-in WordPress features. Therefore, I thought of building a complete application, explaining each and every aspect of web development.

Throughout this book, we will develop an online portfolio management system for web development-related professionals. This application can be considered as a mini version of a basic social network. We will be starting the development of this application from Chapter 2, Implementing Membership Roles, Permissions, and Features.

Planning is a crucial task in web development, in which we will save a lot of time and avoid potential risks in the long run. First, we need to get a basic idea about the goal of this application, features and functionalities, and the structure of components to see how it fits into WordPress.

Application goals and target audience

Developers and designers who work online as freelancers know the importance of a personal profile to show your skills for improved reputation. However, most people, including experts who work full-time jobs don't maintain such profiles, and hence get unnoticed among co-developers. The application developed throughout this book is intended to provide the opportunity for web professionals to create their public profiles and connect with the experts in the field.

This application will be targeted towards all the people who are involved in web development and design. I believe that both output of this application and the contents of the book will be ideal for the PHP developers who want to jump into WordPress application development.

Planning the application

Basically, our application consists of both frontend and backend, which is common to most web applications. In the frontend, both registered and unregistered users will have different functionalities based on their user roles. The following diagram shows the structure of our application home page:

The backend will be developed by customizing the built-in admin features of WordPress. Existing and new functionalities of the admin area will be customized based on the user role permissions.

User roles of the application

Application consists of four user roles, including the built-in admin role. User roles and their respective functionalities are explained in the following section:

  • Admin: This manages the application configurations, settings, and capabilities of the users.

  • Developer: This is the user role common to all web professionals who want to make profiles. All the developers will be able to create complete profile details to enhance their reputation.

  • Members: These are normal users who want to use the things created by developers and designers. They will be able to access and download the work made public by developers. Basically, members will have more permission to directly interact with developers, compared to subscribers. Also, we can implement premium content section in future for paid members.

  • Subscribers: These are also normal users who want to follow the activities of their preferred developers. These users will be notified whenever their preferred developers create a new activity within application.

    Note

    Registration is required for all the four user roles in the portfolio management application.

Planning application features and functions

Our main intention of building this application is to learn how WordPress can be adapted to advanced web application development. Therefore, we will be considering various small requirements, rather than covering all aspects of a similar system. Each of the functionalities will be focused on explaining various modules in web applications and the approach of WordPress in building similar functionality.

Let's consider the following list of functions, which we will be developing throughout this book:

  • Developer profile management: Users who register as developers will be given the opportunity to construct their profile by completing content divided into various sections such as services, portfolio, articles, and books.

  • Frontend login and registration: Typically, web applications contain the login and registration in the frontend, whereas WordPress provides it on the admin area. Therefore, custom implementation of login and registration will be implemented in the application frontend.

  • Settings panel: Comprehensive settings panel will be developed for administrators to configure general application settings from the backend.

  • XML API: A large number of popular web applications come up with a fully functional API to allow access to third-party applications. In this application, we will be developing simple API to access the developer details and activities from external sources.

  • Notification service: A simple notification service will be developed to manage subscriptions as well as manage updates about the application activities.

  • Responsive design: With the increase of mobile devices in Internet browsing, more and more applications are converting their apps to suit various devices. So, we will be targeting different devices for fully responsive design from the beginning of the development process.

  • Third-party libraries: Throughout the book, we will be creating functionalities such as OpenAuth login, RSS feed generation, and template management to understand the use of third-party libraries in WordPress.

While these are our main functionalities, we will also develop small features and components on top of them to explain the major aspects of web development.

If you are still not convinced, you can take a look at the various types of WordPress powered web applications at http://www.innovativephp.com/demo/packt/wordpress_applications.

 

Understanding limitations and sticking to guidelines


As with every framework, WordPress has its limitations in developing web applications. Developers need to understand the limitations before deciding to choose the framework for application development.

In this section, we will learn the limitations while building simple guidelines for choosing WordPress for web development. Let's get started!

  • Lack of support for MVC: We talked about the architecture of WordPress and its support for MVC in one of the earlier sections. As a developer, you need to figure out ways to work with WordPress in order to suit web applications. If you are someone who cannot work without MVC, WordPress may not be the best solution for your application.

  • Database migration: If you are well experienced in web development, you will have a pretty good idea about the importance of choosing databases considering the possibilities of migrating to another one in later stages. This can be a limitation in WordPress as it's built in to work with MySql database. Using it with another database will be quite difficult, if not impossible. So, if you need the database to be migrated to some other database, WordPress will not be the best solution.

  • Performance: Performance of your application is something we get to experience in later stages of the project when we go into a live environment. It's important to plan ahead on the performance considerations as it can come through internal and external reasons. WordPress has a built-in database structure and we will use it in most of the projects. It's designed to suit CMS functionality and sticking with the same tables for different types of projects will not provide the optimized table structure. Therefore, performance might be a limitation for critical applications interacting with millions of records each day, unless you optimize your caching, indexing, and other database optimization strategies.

  • Architecture: WordPress runs on an event-driven architecture, packed with features. Often developers misuse the hooks without proper planning, affecting the performance of the application. So, you have to be responsible in planning the database and necessary hooks in order to avoid performance overheads.

  • Regular Updates: WordPress has a very active community involving its development for new features and fixing the issues in existing features. Once a new version of core is released, plugin developers will also update their plugins to be compatible with the latest version. Hence, you need to perform additional tasks to update core, themes, and plugins, which can be a limitation when you don't have a proper maintenance team.

  • Object Oriented Development: Experienced web developers will always look for object-oriented frameworks for development. WordPress started its coding with procedural architecture and now moving rapidly towards object oriented architecture. So, there will be a mix of both procedural and object-oriented code. WordPress also uses a hook-based architecture to provide functionality for both procedural and object-oriented codes. Developers who are familiar with other PHP frameworks might find it difficult to come to terms with the mix of procedural and object-oriented code as well as the hook-based architecture. So, you have to decide whether you are comfortable with its existing coding styles.

If you are a developer or designer who thinks these limitations, can cause major concerns for your projects, WordPress may not be the right solution for you.

 

Building a question-answer interface


Throughout the previous sections, we learned the basics of web application frameworks while looking at how WordPress fits into web development. By now, you should be able to visualize the potential of WordPress for application development and how it can change your career as developers. Being human, we always prefer practical approach to learn new things over the more conventional theoretical approach.

So, I will complete this chapter by converting default WordPress functionality into a simple question-answer interface such as Stack Overflow, to give you a glimpse of what we will develop throughout this book.

Prerequisites for building a question-answer interface

We will be using version 4.2.2 as the latest stable version; this is available at the time of writing this book. I suggest that you set up a fresh WordPress installation for this book, if you haven't already done so.

Tip

Also, we will be using the Twenty Fourteen theme, which is available with default WordPress installation. Make sure that you activate the Twenty Fourteen theme in your WordPress installation.

First, we have to create an outline containing the list of tasks to be implemented for this scenario:

  1. Create questions using the admin section of WordPress.

  2. Allow users to answer questions using comments.

  3. Allow question creators to mark each answer as correct or incorrect.

  4. Highlight the correct answers of each question.

  5. Customize the question list to include a number of answers and number of correct answers.

Now, it's time to get things started.

Creating questions

The goal of this application is to let people submit questions and get answers from various experts in the same field. First off, we need to create a method to add questions and answers. By default, WordPress allows us to create posts and submit comments to the posts. In this scenario, a post can be considered as the question and comments can be considered as the answers. Therefore, we have the capability of directly using normal post creation for building this interface.

However, I would like to choose a slightly different approach by using custom post types plugin, which you can find at http://codex.wordpress.org/Post_Types#Custom_Post_Types, in order to keep the default functionality of posts and let the new functionality be implemented separately without affecting the existing ones. We will create a plugin to implement the necessary tasks for our application:

  1. First off, create a folder called wpwa-questions inside the /wp-content/plugins folder and add a new file called wpwa-questions.php.

  2. Next, we need to add the block comment to define our file as a plugin:

    /*
    Plugin Name: WPWA Questions
    Plugin URI: -
    Description: Question and Answer interface for developers
    Version: 1.0
    Author: Rakhitha Nimesh
    Author URI: http://www.innovativephp.com/
    License: GPLv2 or later
    Text Domain: wpwa-questions
    */
  3. Having created the main plugin file, we can move into creating a custom post type called wpwa-question using the following code snippet.

  4. Include this code snippet in your wpwa-questions.php file of the plugin:

    add_action('init', 'register_wp_questions');
    function register_wp_questions() {
      $labels = array(
      'name' => __( 'Questions', 'wpwa_questions' ),
      'singular_name' => __( 'Question', 'wpwa_questions'),
      'add_new' => __( 'Add New', 'wpwa_questions'),
      'add_new_item' => __( 'Add New Question', 'wpwa_questions'),
      'edit_item' => __( 'Edit Questions', 'wpwa_questions'),
      'new_item' => __( 'New Question', 'wpwa_questions'),
      'view_item' => __( 'View Question', 'wpwa_questions'),
      'search_items' => __( 'Search Questions', 'wpwa_questions'),
      'not_found' => __( 'No Questions found', 'wpwa_questions'),
      'not_found_in_trash' => __( 'No Questions found in Trash', 'wpwa_questions'),
      'parent_item_colon' => __( 'Parent Question:', 'wpwa_questions'),
      'menu_name' => __( 'Questions', 'wpwa_questions'),
      );
      $args = array(
      'labels' => $labels,
      'hierarchical' => true,
      'description' => __( 'Questions and Answers', 'wpwa_questions'),
      'supports' => array( 'title', 'editor', 'comments' ),
      'public' => true,
      'show_ui' => true,
      'show_in_menu' => true,
      'show_in_nav_menus' => true,
      'publicly_queryable' => true,
      'exclude_from_search' => false,
      'has_archive' => true,
      'query_var' => true,
      'can_export' => true,
      'rewrite' => true,
      'capability_type' => 'post'
      );
    register_post_type( 'wpwa_question', $args );
    }

    This is the most basic and default code for custom post type creation, and I assume that you are familiar with the syntax. We have enabled title, editor, and comments in the support section of the configuration. These fields will act the role of question title, question description, and answers. Other configurations contain the default values and hence explanations will be omitted. If you are not familiar, make sure to have a look at documentation on custom post creation at http://codex.wordpress.org/Function_Reference/register_post_type.

    Note

    Beginner- to intermediate-level developers and designers tend to include the logic inside the functions.php file in the theme. This is considered a bad practice as it becomes extremely difficult to maintain because your application becomes larger. So, we will be using plugins to add functionality throughout this book and drawbacks of the functions.php technique will be discussed in later chapters.

  5. Once the code is included, you will get a new section on the admin area for creating questions. This section will be similar to the posts section inside the WordPress admin. Add few questions and insert some comments using different users before we move into the next stage.

Before we go into the development of questions and answers, we need to make some configurations so that our plugin works without any issues. Let's look at the configuration process:

  1. First, we have to look at the comment-related settings inside Discussion Settings the WordPress Settings section. Here, you can find a setting called Before a comment appears.

  2. Disable both checkboxes so that users can answer and get their answers displayed without approval process. Depending on the complexity of application, you can decide whether to enable these checkboxes and change the implementation.

  3. The second setting we have to change is the Permalinks. Once we create a new custom post type and view it on browser, it will redirect you to a 404 page not found page. Therefore, we have to go to the Permalinks section of WordPress Settings and update the Permalinks using the Save Changes button. This won't change the Permalinks. However, this will flush the rewrite rules so that we can use the new custom post type without 404 errors.

Now, we can start working with the answer-related features.

Customizing the comments template

Usually, the comments section is designed to show comments of a normal post.

While using comments for custom features such as answers, we need to customize the existing template and use our own designs.

  1. So, open the comments.php file inside the Twenty Fourteen theme.

  2. Navigate through the code and you will find a code section similar to the following one:

    wp_list_comments( array(
      'style' => 'ol',
      'short_ping' => true,
      'avatar_size' => 34,
    ) );
  3. First, we need to customize the existing comments list to suit the requirements of the answers list. By default, WordPress will use the wp_list_comments function inside the comments.php file to show the list of answers for each question. We need to modify the answers list in order to include the answer status button. So, we will change the previous implementation as following:

    if(get_post_type( $post ) == "wpwa_question"){
      wp_list_comments('avatar_size=60&type=comment&callback=wpwa_comment_list&style=ol');
    }else{
      wp_list_comments( array(
        'style' => 'ol',
        'short_ping' => true,
        'avatar_size' => 34,
      ) );
    }
  4. Here, we will include a conditional check for the post type in order to choose the correct answer list generation function. When the post type is wpwa_question, we call the wp_list_comments function with the callback parameter defined as wpwa_comment_list, which will be the custom function for generating answers list.

    Note

    Arguments of the wp_list_comments function can be either an array or string. Here, we have preferred array-based arguments over string-based arguments.

In the next section, we will be completing the customization of comments template by adding answer statuses and allowing users to change the statuses.

Changing the status of answers

Once the users provide their answers, the creator of the question should be able to mark them as correct or incorrect answers. So, we will implement a button for each answer to mark the status. Only the creator of the questions will be able to mark the answers. Once the button is clicked, an AJAX request will be made to store the status of the answer in the database.

Implementation of the wpwa_comment_list function goes inside the wpwa-questions.php file of our plugin. This function contains lengthy code, which is not necessary for our explanations. Hence, I'll be explaining the important sections of the code. It's ideal to work with the full code for the wpwa_comment_list function from the source code folder:

function wpwa_comment_list( $comment, $args, $depth ) {
  global $post;
  $GLOBALS['comment'] = $comment;
  // Get current logged in user and author of question
  $current_user = wp_get_current_user();
  $author_id = $post->post_author;
  $show_answer_status = false;
  // Set the button status for authors of the question
  if ( is_user_logged_in() && $current_user->ID == $author_id ) {
      $show_answer_status = true;
    }
    // Get the correct/incorrect status of the answer
    $comment_id = get_comment_ID();
    $answer_status = get_comment_meta( $comment_id, "_wpwa_answer_status", true );
    // Rest of the Code
}

The wpwa_comment_list function is used as the callback function of the comments list, and hence, it will contain three parameters by default. Remember that the button for marking the answer status should be only visible to the creator of the question.

In order to change the status of answers, follow these steps:

  1. First, we will get the current logged-in user from the wp_get_current_user function. Also, we can get the creator of the question using the global $post object.

  2. Next, we will check whether the logged-in user created the question. If so, we will set show_answer_status to true. Also, we have to retrieve the status of the current answer by passing the comment_id and _wpwa_answer_status keys to the get_comment_meta function.

  3. Then, we will have to include the common code for generating comments list with necessary condition checks.

  4. Open the wpwa-questions.php file of the plugin and go through the rest of wpwa_comment_list function to get an idea of how comments loop works.

  5. Next, we have to highlight correct answers of each question and I'll be using an image as the highlighter. In the source code, we use following code after the header tag to show the correct answer highlighter:

    <?php
      // Display image of a tick for correct answers
      if ( $answer_status ) {
        echo "<div class='tick'><img src='".plugins_url( 'img/tick.png', __FILE__ )."' alt='Answer Status' /></div>";
      }
    ?>
  6. In the source code, you will see a <div> element with the class reply for creating the comment reply link. We will need to insert our answer button status code right after this, as shown in the following code:

    <div>
      <?php
      // Display the button for authors to make the answer as correct or incorrect
      if ( $show_answer_status ) {
        $question_status = '';
        $question_status_text = '';
        if ( $answer_status ) {   
          $question_status = 'invalid';
          question_status_text = __('Mark as Incorrect','wpwa_questions');
        } else {
          $question_status = 'valid';
          $question_status_text = __('Mark as Correct','wpwa_questions');
        }
    ?>
      <input type="button" value="<?php echo $question_status_text; ?>"  class="answer-status answer_status-<?php echo $comment_id; ?>" 
      data-ques-status="<?php echo $question_status; ?>" />
      <input type="hidden" value="<?php echo $comment_id; ?>" class="hcomment" />
      <?php
      }
      ?>
    </div>
  7. If the show_answer_status variable is set to true, we get the comment ID, which will be our answer ID, using the get_comment_ID function. Then, we will get the status of answer as true or false using the _wpwa_answer_status key from the wp_commentmeta table.

  8. Based on the returned value, we will define buttons for either Mark as Incorrect or Mark as Correct. Also, we will specify some CSS classes and HTML5 data attribute to be used later with jQuery.

  9. Finally, we keep the comment_id in a hidden variable called hcomment.

  10. Once you include the code, the button will be displayed for the author of the question, as shown in the following screen:

  11. Next, we need to implement the AJAX request for marking the status of the answer as true or false.

Before this, we need to see how we can include our scripts and styles into WordPress plugins. Here is the code for including custom scripts and styles for our plugin. Copy the following code into the wpwa-questions.php file of your plugin:

function wpwa_frontend_scripts() {
  wp_enqueue_script( 'jquery' );
  wp_register_script( 'wpwa-questions', plugins_url( 'js/questions.js', __FILE__ ), array('jquery'), '1.0', TRUE );
  wp_enqueue_script( 'wpwa-questions' );
  wp_register_style( 'wpwa-questions-css', plugins_url( 'css/questions.css', __FILE__ ) );
  wp_enqueue_style( 'wpwa-questions-css' );
  $config_array = array(
    'ajaxURL' => admin_url( 'admin-ajax.php' ),
    'ajaxNonce' => wp_create_nonce( 'ques-nonce' )
  );
  wp_localize_script( 'wpwa-questions', 'wpwaconf', $config_array );
}
add_action( 'wp_ajax_mark_answer_status', 'wpwa_mark_answer_status' );

WordPress comes in-built with an action hook called wp_enqueue_scripts, for adding JavaScript and CSS files. The wp_enqueue_script action is used to include script files into the page while the wp_register_script action is used to add custom files. Since jQuery is built-in to WordPress, we can just use the wp_enqueue_script action to include jQuery into the page. We also have a custom JavaScript file called questions.js, which will contain the functions for our application.

Inside JavaScript files, we cannot access the PHP variables directly. WordPress provides a function called wp_localize_script to pass PHP variables into script files. The first parameter contains the handle of the script for binding data, which will be wp_questions in this scenario. The second parameter is the variable name to be used inside JavaScript files to access these values. The third and final parameters will be the configuration array with the values.

Then, we can include our questions.css file using the wp_register_style and wp_enqueue_style functions, which will be similar to JavaScript, file inclusion syntax, we discussed previously. Now, everything is set up properly to create the AJAX request.

Saving the status of answers

Once the author clicks the button, the status has to be saved to the database as true or false depending on the current status of the answer. Let's go through the jQuery code located inside the questions.js file for making the AJAX request to the server:

jQuery(document).ready(function($) {
  $(".answer-status").click( function() {
    $(body).on("click", ".answer-status" , function() {
      // Get the button object and current status of the answer
      var answer_button = $(this);
      var answer_status  = $(this).attr("data-ques-status");
      // Get the ID of the clicked answer using hidden field
      var comment_id = $(this).parent().find(".hcomment").val();
      var data = {
      "comment_id":comment_id,
      "status": answer_status
    };
  // Create the AJAX request to save the status to database
  $.post( wpwaconf.ajaxURL, {
    action:"mark_answer_status",
    nonce:wpwaconf.ajaxNonce,
    data : data,
  }, function( data ) {
    if("success" == data.status){
      if("valid" == answer_status){
         answer_buttonval("Mark as Incorrect");
         answer_button.attr(" data-ques-status","invalid");
      }else{
        answer_button.val("Mark as Correct");
        answer_button.attr(" data-ques-status","valid");
        }
      }
    }, "json");
  });
});

The preceding code creates a basic AJAX request to the mark_answer_status action. Most of the code is self-explanatory and code comments will help you to understand the process.

Note

The important thing to note here is that we have used the configuration settings assigned in the previous section, using the wpwaconf variable. Once a server returns the response with success status, the button will be updated to contain new status and display text.

The next step of this process is to implement the server-side code for handling AJAX request. First, we need to define AJAX handler functions using the WordPress add_action function. Since logged-in users are permitted to mark the status, we don't need to implement the add_action function for wp_ajax_nopriv_{action}:

add_action( 'wp_ajax_mark_answer_status', 'wpwa_mark_answer_status' );

Implementation of the wpwa_mark_answer_status function is given in the following code:

function wpwa_mark_answer_status() {
  $data = isset( $_POST['data'] ) ? $_POST['data'] : array();
  $comment_id     = isset( $data["comment_id"] ) ? absint($data["comment_id"]) : 0;
  $answer_status  = isset( $data["status"] ) ? $data["status"] : 0;
  // Mark answers in correct status to incorrect
  // or incorrect status to correct
  if ("valid" == $answer_status) {
    update_comment_meta( $comment_id, "_wpwa_answer_status", 1 );
  } else {
  update_comment_meta( $comment_id, "_wpwa_answer_status", 0 );
  }
  echo json_encode( array("status" => "success") );
  exit;
}

We can get the necessary data from the $_POST array and use to mark the status of the answer using the update_comment_meta function. This example contains the most basic implementation of data saving process. In real applications, we need to implement necessary validations and error handling.

Now, the author who asked the question has the ability to mark answers as correct or incorrect. So, we have implemented a nice and simple interface for creating a question-answer site with WordPress. The final task of the process will be the implementation of questions list.

Generating a question list

Usually, WordPress uses the archive.php file of the theme, for generating post lists of any type. We can use a file called archive-{post type}.php for creating different layouts for different post types:

  1. Here, we will create a customized layout for our questions.

  2. Make a copy of the existing archive.php file of the TwentyFourteen theme and rename it as archive-wpwa_question.php. Here, you will find the following code section:

    get_template_part( 'content', get_post_format() );
  3. The TwentyFourteen theme uses a separate template for generating the content of each post type. We cannot modify the existing content.php file as it affects all kinds of posts. So, create a custom template called content-questions.php by duplicating the content.php file and change the preceding code to the following:

    get_template_part( 'content-wpwa_question', get_post_format() );
  4. Finally, we need to consider the implementation of content-wpwa_question.php file. In the questions list, only the question title will be displayed, and therefore, we don't need the content of the post. So, we have to either remove or comment the the_excerpt and the_content functions of the template. We can comment the following line within this template:

    the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentyfourteen' ) );
  5. Then, we will create our own metadata by adding the following code to the <div> element with the entry-content class:

    <div class="answer_controls"><?php comments_popup_link(__('No Answers &darr;', 'responsive'), __('1 Answer &darr;', 'responsive'), __('% Answers &darr;', 'responsive')); ?>
    </div>
    <div class="answer_controls">
    <?php wpwa_get_correct_answers(get_the_ID()); ?>
    </div>
    <div class="answer_controls">
    <?php echo   get_the_date(); ?>
    </div>
    <div style="clear: both"></div>

    The first container will make use of the existing comments_popup_link function to get the number of answers given for the questions.

  6. Then, we need to display the number of correct answers of each question. The custom function called wpwa_get_correct_answers is created to get the correct answers. The following code contains the implementation of the wpwa_get_correct_answers function inside the plugin:

    function wpwa_get_correct_answers( $post_id ) {
      $args = array(
        'post_id'   => $post_id,
        'status'    => 'approve',
        'meta_key'  => '_wpwa_answer_status',
        'meta_value'=> 1,
      );
      // Get number of correct answers for given question
      $comments = get_comments( $args );
      printf(__('<cite class="fn">%s</cite> correct answers'), count( $comments ) );
    }

    We can set the array of arguments to include the conditions to retrieve the approved answers of each post, which contains the correct answers. The number of results generated from the get_comments function will be returned as correct answers. Now, you should have a question list similar to following image:

Throughout this section, we looked at how we can convert the existing functionalities of WordPress for building a simple question-answer interface. We took the quick and dirty path for this implementation by mixing HTML and PHP code inside both, themes and plugins.

Note

I suggest that you go through the Chapter01 source code folder and try this implementation on your own test server. This demonstration was created to show the flexibility of WordPress. Some of you might not understand the whole implementation. Don't worry as we will develop a web application from scratch using detailed explanation in the following chapters.

 

Enhancing features of the questions plugin


In the previous sections, we illustrated how to quickly adapt WordPress into different kind of implementations by customizing its core features. However, I had to limit the functionality to the most basic level in order to keep this chapter short and interesting for the beginners. If you are willing to improve it, you can try other new features of such an application. Here, we will be looking at some of the enhancements to this plugin and how we can use core WordPress features to implement them.

Customizing the design of questions

This is one of the major requirements in such an application. Here, we have a very basic layout and it's difficult to know whether this is a question or just a normal post. Consider the following screenshot for a well-designed question interface:

Remember that we customized the comments list for adding new options. Similarly, we can customize the design of questions to create an interface such as the previous screenshot by using a separate template file for the questions custom post type. We have to create a file called single-wpwa_question.php and change the design and functionality as we want.

Categorizing questions

Categories allow us to filter the results and limit it to a certain extent. It's an essential feature in the question-answer application so that users can directly view questions related to their topic instead of browsing all the questions. WordPress provides categories by default. However, these categories are mainly intended for posts. Therefore, we have to use custom taxonomies to create categories for custom post types such as questions. More details about taxonomies will be discussed in the following chapters.

Approving and rejecting questions

Currently, our application can post questions without any approval process. However, this is not the ideal implementation as it can create a lot of spam questions. In a well-built application, there should be a feature to approve/reject questions when needed. This feature can be easily built with WordPress admin lists. We have a list of questions in the backend, and we can use the Bulk Actions dropdown on top to add custom actions and implement this feature.

Adding star rating to answers

The author who asked the question can mark the answers as correct or incorrect. However, there can be scenarios where answers are not marked as correct are more suitable than answers marked as correct. Therefore, we can introduce star rating features to answers so that public can rate the answers. The person who looks for the answer can consider the rating before choosing answers. Implementation of this requirement is similar to the functionality of the Mark as Correct button. We have to get a js plugin for star rating and integrate to the interface through the wpwa_comment_list function. Then we can use AJAX to mark the status of answers.

We have looked at some of the possible enhancements to such an application. You can think of many more such functionalities and implement them in your own version.

In the following chapters, we'll see the limitations in this approach in complex web applications and how we can organize things better to write quality and maintainable code.

 

Summary


Our main goal was to find how WordPress fits into web application development. We started this chapter by identifying the CMS functionalities of WordPress. We explored the features and functionalities of popular full stack frameworks and compared them with the existing functionalities of WordPress.

Then, we looked at the existing components and features of WordPress and how each of those components fit into a real-world web application. We also planned the portfolio management application requirements and identified the limitations in using WordPress for web applications.

Finally, we converted the default interface into a question-answer interface in a rapid process using existing functionalities.

By now, you should be able to decide whether to choose WordPress for your web application, visualize how your requirements fits into components of WordPress, and identify and minimize the limitations.

In the next chapter, we will start developing the portfolio management application with the user management. Before we go there, I suggest that you research user management features of other frameworks and look at your previous projects to identify the functionalities.

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 (5 reviews total)
Excellent. Have just switched from supporting Joomla to WordPress and was looking for some break-in material which I could read away from work on a kindle. Purchased as an eBook along with some other complimentary titles during recent $5 bonanza and at this price I cannot possibly fault.
not so relevant to my work
i love first edition than second edition
WordPress Web Application Development
Unlock this book and the full library FREE for 7 days
Start now