Home Web Development Wordpress Web Application Development - Third Edition

Wordpress Web Application Development - Third Edition

By Rakhitha Nimesh Ratnayake
books-svg-icon Book
eBook $39.99 $27.98
Print $48.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 $39.99 $27.98
Print $48.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
WordPress is one of the most rapidly expanding markets on the Web. Learning how to build complex and scalable web applications will give you the ability and knowledge to step into the future of WordPress. WordPress 4.7 introduces some exciting new improvements and several bug fixes, which further improve the entire development process.This book is a practical, scenario-based guide to expanding the power of the WordPress core modules to develop modular and maintainable real-world applications from scratch. This book consistently emphasizes adapting WordPress features into web applications. It will walk you through the advanced usages of existing features such as access controlling; database handling; custom post types; pluggable plugins; content restrictions; routing; translation; caching; and many more, while you build the backend of a forum management application. This book begins by explaining how to plan the development of a web application using WordPress' core features. Once the core features are explained, you will learn how to build an application by extending them through custom plugin development. Finally, you will explore advanced non-functional features and application integration. After reading this book, you will have the ability to develop powerful web applications rapidly within limited time frames.
Publication date:
May 2017
Publisher
Packt
Pages
536
ISBN
9781787126800

 

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, the dream of using this amazing framework for web application development is becoming possible.

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 the WordPress framework to build web applications using a rapid process.

Basically, this book will be important for developers from two different perspectives. On the 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 forum management application
  • Understanding limitations and sticking with guidelines
  • Building a question-answer interface
  • Enhancing features of the questions plugin

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 it continued to improve until it became the most popular blogging tool. Later, it continued to improve as a CMS (Content Management System) and now has a reputation for being the most popular CMS for over five years. 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. Also, the most recent introduction of the REST API is a major indication that WordPress is moving towards the direction of building web applications. The combination of the REST API and modern JavaScript frameworks will enable developers to build complex web applications with WordPress.

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

  1. The plugin-based architecture for adding independent features and the existence of over 40,000 open source plugins
  2. The ability to create unlimited free websites at www.wordpress.com and use the basic WordPress features
  3. A super simple and easy-to-access administration interface
  4. A fast learning curve and comprehensive documentation for beginners
  5. A rapid development process involving themes and plugins
  6. An active development community with awesome support
  7. The flexibility in building websites with its themes, plugins, widgets, and hooks
  8. The availability of large premium theme and plugin marketplaces for developers to sell advanced plugin/themes and users to build advanced sites with those premium plugins/themes without needing a developer

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 in 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 build 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 the 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 processes to make it work like an 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 its 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, the unavailability of MVC architecture doesn't mean that we cannot develop quality applications with WordPress. There are many other ways to separate concerns in WordPress applications.

On the other hand WordPress, 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 a 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 a number of WordPress features directly related to web development, even though it is meant to create websites.

Let's get a brief introduction to the WordPress core features to see how they fit 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 make 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 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 from a 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 build search engine-friendly URLs.

XML-RPC API

Building an API is essential for allowing third-party access to our application. WordPress provides a 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.

REST API

The REST API makes it possible to give third-party access to the application data, similar to XML-RPC API. This API uses easy to understand HTTP requests and JSON format, making it easier to communicate with WordPress applications. JavaScript is becoming the modern trend in developing applications. So, the availability of JSON in the REST API will allow external users to access and manipulate WordPress data within their JavaScript-based applications.

Caching

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

Scheduling

As developers, you might have worked with cron jobs for executing certain tasks at specified intervals. WordPress offers the 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 to a 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 data. Flexibility is one of the key reasons for the higher popularity of WordPress compared to other CMSs. 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 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 from 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 image:

Having looked at the structure, it's obvious that the Header, Footer, and the Main Content areas 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. The 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 to target the specific requirements of a client. On the other hand, a product is an application created based on the common set of requirements for a 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 among other competitive frameworks. Most of you should be familiar with using the 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

The dashboard is the location where all the users get redirected, once logged into the admin area. Usually, it contains dynamic widget areas with the most important data of your application. The 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 the 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 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 the 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 the 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 the main template into multiple sections. Also, these types of widgetized areas become handy in applications where the 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

Under normal circumstances, WordPress developers use functions that involve application logic scattered across theme files and plugins. Some developers even 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 themes 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. Since there are over 40,000 free plugins and a large number of premium plugins, sometimes you don't have to develop anything for WordPress applications. You can just use a number of plugins and integrate them properly to build advanced applications.

The role of widgets

The official documentation of WordPress refers to widgets as a component that adds content and features to your sidebar. From 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. Modern WordPress themes provide a wide range of built-in widgets for advanced functionality, making it much more easier to build applications. 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 have 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, we can plan our application developed throughout this book.

 

A development plan for the forum 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 forum management system for creating public forums or managing a support forum for a specific product or service. This application can be considered as a mini version of a powerful forum system like bbPress. 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, through 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 the application, its features and functionalities, and the structure of components to see how it fits into WordPress.

Application goals and target audience

Anyone who is using the Internet on a day-to-day basis knows the importance of online discussion boards, also known as forums. These forums allow us to participate in a large community and discuss common matters, either related to a specific subject or a product. The application developed throughout this book is intended to provide a simple and flexible forum management application using a WordPress plugin with the goals of:

  • Learning to develop a forum application
  • Learning to use features of various online forums
  • Learning to manage a forum for your product or service

This application will be targeted towards all the people who have participated in an online forum or used a support system of a product they purchased. I believe that both output of this application and the contents of the book will be ideal for 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 image 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

The 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: Users of this role manage the application configurations, settings, and capabilities of the users.
  • Moderator: Users of this role manage the forums and topics. These users can create topics, manage topic statuses, and provide admin level feedback in case of a support forum.
  • Premium Members: These users gain access to the forums by purchasing a package or subscription. These users will have premium forum features and access to all content without restrictions.
  • Free Members: These are normal registered users who want to access the forums. These users will have limited access to content and forum features.
Registration is required for all four user roles in the forum management application.

Planning application features and functions

Our main intention for 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:

  • Forum user profile management: Users who register for forums will have a profile where they can edit personal details and view their forum topic details without going into the forum.
  • Forums and Topics management: The application provides the ability to create forums and topics under these forums. Admin staff will be responsible for creating and closing forum tickets while users will have the ability to create their own tickets.
  • Frontend login and registration: Typically, web applications contain the login and registration in the frontend, whereas WordPress provides it in the admin area. Therefore, custom implementation of login and registration will be implemented in the application frontend with the support of social login.
  • Manage forum topic permissions: Various features will be developed to provide restrictions to forum and topic features for different user levels.
  • Joining a Forum: Users will have features to join a forum and admins will have features to approve/reject user requests.
  • Settings panel: A comprehensive settings panel will be developed for administrators to configure general application settings from the backend.
  • REST 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 a simple API to access the developer details and activities from external sources.
  • Notification service: A simple notification service will be developed to manage e-mail notifications on new topics in forums and responses to subscribed topics in forums.
  • Responsive design: With the increase of mobile devices for Internet browsing, more and more applications are converting their apps to suit various devices. So, we will be targeting different devices for a 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 to work with MySQL databases. 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.
  • Security: This is one of the most important aspects of application development. WordPress is open source and many sites uses free plugins without proper security and code checks. Therefore, when proper security measures are not implemented, potential hackers and programs can identify the vulnerabilities and generate security threats. Many people tend to think WordPress is insecure due to such reasons.
  • Performance: The performance of your application is something we get to experience in the later stages of the project when we go into a live environment. It's important to plan ahead on performance considerations as they 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 the 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 the 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 is now moving rapidly toward 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 could 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 a developer. Being human, we always prefer a practical approach to learning 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.7.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.

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

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

  • Create questions using the admin section of WordPress
  • Allow users to answer questions using comments
  • Allow question creators to mark each answer as correct or incorrect
  • Highlight the correct answers of each question
  • 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 the 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 using WordPress Custom Post Types and Comments
Version: 1.0
Author: Rakhitha Nimesh
Author URI: http://www.wpexpertdeveloper.com/
License: GPLv2 or later
Text Domain: wpwa-questions
*/
  1. Having created the main plugin file, we can now create the structure of our plugin with the necessary settings as shown in the following code section:
        if( !class_exists( 'WPWA_Questions' ) ) {     
class WPWA_Questions{
private static $instance;
public static function instance() {

if ( ! isset( self::$instance ) && ! ( self::$instance instanceof WPWA_Questions ) ) {
self::$instance = new WPWA_Questions();
self::$instance->setup_constants();
self::$instance->includes();

add_action('admin_enqueue_scripts',array(self::$instance,'load_admin_scripts'),9);
add_action('wp_enqueue_scripts',array(self::$instance,'load_scripts'),9);

}
return self::$instance;
}
public function setup_constants() {
if ( ! defined( 'WPWA_VERSION' ) ) {
define( 'WPWA_VERSION', '1.0' );
}
if ( ! defined( 'WPWA_PLUGIN_DIR' ) ) {
define('WPWA_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
}
if ( ! defined( 'WPWA_PLUGIN_URL' ) ) {
define( 'WPWA_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
}
}
public function load_scripts(){ }
public function load_admin_scripts(){ }
private function includes() { }
public function load_textdomain() { }
}
}
  1. First, we create a class called WPWA_Questions as the main class of the question-answer plugin. Then we define a variable to hold the instance of the class and use the instance function to generate an object from this class. This static function and the private instance variables make sure that we only have one instance of our plugin class. We have also included the necessary function calls and filters in this function.
  2. These functions are used to handle the most basic requirements of any WordPress plugin. Since they are common to all plugins, we keep these functions inside the main file. Let's look at the functionality of these functions:
  • setup_constants: This function is used to define the constants of the application such as version, plugin directory path, and plugin directory URL
  • load_scripts: This function is used to load all the plugin specific scripts and styles on the frontend of the application
  • load_admin_scripts: This function is used to load all the plugin specific scripts and styles on the backend of the application
  • includes: This function is used to load all the other files of the plugin
  • load_text_domain: This function is used to configure the language settings of the plugin
  1. Next, we initialize the plugin by calling the following code after the class definition:
        function WPWA_Questions() {
global $wpwa;
$wpwa = WPWA_Questions::instance();
}
WPWA_Questions();
  1. Having created the main plugin file, we can move into creating a custom post type called wpwa-question using the following code snippet. Include this code snippet in your WPWA_Questions class file of the plugin:
        public 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 as the roles 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.

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 the drawbacks of the functions.php technique will be discussed in later chapters.
  1. Then, you have to add the following code inside the instance function of WPWA_Questions class to initialize the custom post type creation code:
        add_action('init',
array(self::$instance,'register_wp_questions'));
  1. 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 a 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 in 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 the approval process. Depending on the complexity of application, you can decide whether to enable these checkboxes and change the implementation.
  1. The second setting we have to change is the Permalinks. Once we create a new custom post type and view it in a 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 the 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 by performing the following steps:

  1. So, open the comments.php file inside the Twenty Seventeen theme.
  2. Navigate through the code and you will find a code section similar to the following one:
        wp_list_comments( array( 
'avatar_size' => 100,
'style' => 'ol',
'short_ping' => true,
'reply_text' => twentyseventeen_get_svg( array( 'icon' => 'mail- reply' ) ) . __( 'Reply', 'twentyseventeen' ),
) );
  1. We need to modify this section of code to suit the requirements of the answers list. The simplest method is to edit the comments.php file of the theme and add the custom code changes. However, modifying core theme or plugin files is considered a bad practice since you lose the custom changes on theme or plugin updates. So, we have to provide this template within our plugin to make sure that we can update the theme when needed.
  2. Let's copy the comments.php file from the Twenty Seventeen theme to the root of our plugin folder. 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 to the following in the comments.php file we added inside our plugin:
        <?php 
global $wpwa;

if(get_post_type( $post ) == "wpwa_question"){
wp_list_comments(array('avatar_size' => 100 , 'type' => 'comment', 'callback' => array($wpwa, 'comment_list')));

}else{
wp_list_comments( array(
'avatar_size' => 100,
'style' => 'ol',
'short_ping' => true,
'reply_text' => twentyseventeen_get_svg( array( 'icon' => 'mail-reply' ) ) . __( 'Reply', 'twentyseventeen' ),
) );
}
?>
  1. 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 comment_list, which will be the custom function for generating the answers list.
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.
  1. We have a custom comments.php file inside the plugin. However, WordPress is not aware of the existence of this file and hence will load the original comments.php file within the theme. So, we have to include our custom template by adding the following filter code to instance the function:
        add_filter('comments_template',  
array(self::$instance,'load_comments_template'));
  1. Finally, we have to implement the load_comments_template function inside the main class of the plugin to use our comments template from the plugins folder:
        public function load_comments_template($template){ 
return WPWA_PLUGIN_DIR.'comments.php';
}

In the next section, we will be completing the customization of the 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 comment_list function goes inside the main class of 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 comment_list function from the source code folder:

        function comment_list( $comment, $args, $depth ) { 
global $post;
$GLOBALS['comment'] = $comment;

$current_user = wp_get_current_user();
$author_id = $post->post_author;
$show_answer_status = false;

if ( is_user_logged_in() && $current_user->ID == $author_id ){
$show_answer_status = true;
}
$comment_id = get_comment_ID();
$answer_status = get_comment_meta( $comment_id,
"_wpwa_answer_status", true );

// Rest of the Code
}

The 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 a comments list with the necessary condition checks.
  4. Open the wpwa-questions.php file of the plugin and go through the rest of the comment_list function to get an idea of how the comments loop works.
  5. Next, we have to highlight the correct answers of each question and I'll be using an image as the highlighter. In the source code, we use the 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>";
}
?>
  1. 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>
  1. 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.
  2. 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 attributes to be used later with jQuery.
  3. Finally, we keep the comment_id in a hidden variable called hcomment.
  1. Once you include the code, the button will be displayed for the author of the question, as shown in the following screen:
  1. 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. We added empty functions to include the scripts and styles while preparing the structure of this plugin. Here is the code for including custom scripts and styles for our plugin inside the load_scripts function we created earlier. Copy the following code into the load_scripts function of the wpwa-questions.php file of your plugin:

    public function load_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
);
}

WordPress comes with an action hook built-in 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() {

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
};

$.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");
});
});

Let's understand the implementation of saving the answer status. This code snippet executes every time a user clicks the button to change the status. We get the current status of the answer by using the data-ques-status attribute of the button. Next, we get the ID of the answer using the hidden field with hcomment as the CSS class. Then, we send the data through an AJAX request to the mark_answer_status action.

Once the AJAX response is received, we display the new status of the answer and update the data attribute of the button with the new status.

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 the new status and display text.

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

    add_action('wp_ajax_mark_answer_status',  
array(self::$instance,'mark_answer_status'));

Then, we need to add the mark_answer_status function inside the main class. Implementation of the mark_answer_status function is given in the following code:

    function 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 it to mark the status of the answer using the update_comment_meta function. This example contains the most basic implementation of the 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 the 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. Here, we will create a customized layout for our questions. The simplest solution is to copy the archive file and create a new file called archive-{post type}.php inside the theme. However, it's not the ideal way to create a custom template due to the reasons we discussed while creating the comments.php file. So, we have to use a plugin specific template and override the default behavior of the archive file. Refer to the following steps:

  1. Make a copy of the existing archive.php file of the TwentySeventeen theme, copy it to the root folder of the plugin, and rename it questions-list-template.php. Here, you will find the following code section:
        get_template_part( 'template-parts/post/content', get_post_format() ); 
  1. The TwentySeventeen theme uses a separate template for generating the content of each post type. We have to replace this with our own template inside the plugin. The get_template_part function is only used to load the theme specific template. So, we can't use it to load a template file from a plugin. The solution is to include the template file using the following code:
        require WPWA_PLUGIN_DIR . 'content.php'; 
  1. Next, we have to create the content template by copying the content.php file of the theme from the template-parts/post/content folder to the root folder of our plugin.
  2. Finally, we need to consider the implementation of the content.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( sprintf( 
__( 'Continue reading<span class="screen-reader-text"> "%s"</span>', 'twentyseventeen' ), get_the_title()
) );
  1. 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;', 'twentyseventeen '),
__('1 Answer &darr;', 'responsive'), __('% Answers &darr;',
'twentyseventeen')); ?>
</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.

  1. Then, we need to display the number of correct answers of each question. The custom function called get_correct_answers is created to get the correct answers. The following code contains the implementation of the get_correct_answers function inside the main class of the plugin:
        function 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.

We have completed the code for displaying the questions list. However, you will still see a list similar to the default posts list. The reason for that is we created a custom template and WordPress is not aware of its existence. So, the default template file is loaded instead of our custom template.

  1. We need to override the existing archive template of WordPress by adding the following action to the instance function of the main plugin class:
        add_filter( 'archive_template',  
array(self::$instance,'questions_list_template' ));
  1. Here, we have the implementation of the questions_list_template function inside the main class of the plugin:
        public function questions_list_template($template){ 
global $post;

if ( is_post_type_archive ( 'wpwa_question' ) ) {
$template = WPWA_PLUGIN_DIR . '/questions-list-template.php';
}
return $template;
}

This function overrides the archive template when the questions list is displayed and keeps the default template for posts lists or any other custom post type lists.

Now, you should have a question list similar to the following screenshot:

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.

I suggest that you go through the Chapter 1, WordPress as a Web Application Framework, 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 a 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 kinds 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 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 them 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 the 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 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 fits into a real-world web application. We also planned the forum 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, without interrupting the default behavior of WordPress and themes.

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

In the next chapter, we will start developing the forum management application with the user management. Before we go there, I suggest that you research the 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 (10 reviews total)
s.o. Alles schnell und unkompliziert. Einzig die Download-Links in der Bestellbestätigung habe ich nichtz gleich als Solche erkannt. Ein kleiner Hinweis im Text wäre ggf. hilfreich.
ワードプレスの本を探していて買ったのですが知らなかった事があったり、日本語の本で勉強した事の復習にもなったのでまだ途中ですがとても良かったです。
Clear and useful book. Lots of informations.
Wordpress Web Application Development - Third Edition
Unlock this book and the full library FREE for 7 days
Start now