WordPress Web Application Development

By Rakhitha Nimesh Ratnayake
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. WordPress As a Web Application Framework

About this book

Developing WordPress-powered websites is one of the standout trends in the modern web development world. The flexibility and power of the built-in features offered by WordPress has made developers turn their attentions to the possibility of using it as a web development framework. This book will act as a comprehensive resource for building web applications with this amazing framework.

"WordPress Web Application Development" is a comprehensive guide focused on incorporating the existing features of WordPress into typical web development. This book is structured towards building a complete web application from scratch. With this book, you will build an application with a modularized structure supported by the latest trending technologies.

"Wordpress Web Application Development" provides a comprehensive, practical, and example-based approach for pushing the limits of WordPress for web applications beyond your imagination.

This book begins by exploring the role of existing WordPress components and discussing the reasons for choosing WordPress for web application development. As we proceed, more focus will be put into adapting WordPress features into web applications with the help of an informal use-case-based model for discussing the most prominent built-in features. While striving for web development with WordPress, you will also learn about the integration of popular client-side technologies such as Backbone, Underscore, and jQuery, and server-side technologies and techniques such as template engines, RSS feeds, Open Auth integration, and more.

After reading this book, you will possess the ability to develop powerful web applications rapidly within limited time frames with the crucial advantage of benefitting low-budget and time-critical projects.

Publication date:
November 2013
Publisher
Packt
Pages
376
ISBN
9781783280759

 

Chapter 1. WordPress As a Web Application Framework

In recent years, WordPress has matured from being the most popular blogging tool 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 become interested in using WordPress, there are discussions and arguments for 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 modules, which can be easily adapted to web application development using some slight modifications. Since you are already reading this book, you are probably someone who is really excited to see how WordPress fits into web application development. Throughout this book, we are going to learn how we can inject the best practices of web development into the WordPress framework to build web applications in a rapid process.

Basically, this book will be important for developers from two different perspectives. On one hand, WordPress developers of beginner level to intermediate level can get the 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 are going to cover the following topics:

  • WordPress as a CMS

  • WordPress as a web development framework

  • Simplifying development with built-in modules

  • Identifying the components of WordPress

  • A development plan for a portfolio management application

  • Understanding limitations and sticking to guidelines

  • Building a question-answer interface

In order to work through 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 on choosing 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. Afterwards, it continued to improve as a CMS (Content Management System) and has a reputation now 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?

No one really knows the answer for this question. But recent versions of WordPress have included popular web development libraries such as Backbone.js and Underscore.js, and developers are even building different types of applications with WordPress. So we can assume that it's moving towards 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 a good idea 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 modules and the existence of over 20,000 open source plugins

  • Super simple and easy-to-access administration interface

  • Fast learning curve and comprehensive documentation for beginners

  • Rapid development process involving themes and plugins

  • 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. But 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, let's 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 development 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 is a list of possible reasons that frameworks become a priority in web application development:

  • They provide stable foundations for building custom functionalities

  • Stable frameworks usually have a large development community with active support

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

  • They have a large number 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 become the framework of choice for most developers. Now let's take a look at how WordPress fits into the boots of the web application framework.

MVC versus event-driven architecture

A vast majority of web development frameworks are built to work with the MVC (Model-View-Controller) architecture, where the 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 that developers refuse to choose it as a development framework. Even though it is not MVC, we can create a custom execution process to make it work like an MVC application. Unlike other frameworks, it won't have the full capabilities of MVC. But unavailability of an MVC architecture doesn't mean that we cannot develop quality applications with WordPress.

WordPress relies on procedural event-driven architecture with its action hooks and filter system. Once the 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 an event-driven architecture, both the model and controller code gets scattered throughout the theme files. In the upcoming chapters, we are going to look at how we can separate these concerns with the event-driven architecture, in order to develop maintainable applications.

 

Simplifying development with built-in modules


As we discussed in the previous section, the quality of a framework depends on its core modules. The more quality you have in 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 modules directly related to web development, even though it was meant to create websites.

Let's get a brief introduction about the WordPress core modules to see how they fit into web application development:

  • User module: The built-in user management module is quite advanced, catering 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. Most full stack frameworks don't have a built-in user module and hence this can be considered as an advantage of using WordPress.

  • File 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. This 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 templating engine, but it does offer a wide range of capabilities from the 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 their 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 plugins. WordPress makes it simple to change the existing routing and choose your own routing, in order to build search engine friendly URLs.

  • XMR-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.

  • Caching: Caching in WordPress can be categorized into two sections; persistent and nonpersistent cache. Nonpersistent caching is provided by the WordPress cache object, while persistent caching is provided through its transient API. Caching techniques in WordPress is a simple comrade 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. Typically, it's used for scheduling future posts. But it can be extended to cater to complex scheduling functionality.

  • Plugins and widgets: The power of WordPress comes with 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 in the remainder of this chapter.

An overall collection of modules and 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 module 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 are going to 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 the WordPress theme

  • The role of the admin dashboard

  • The role of plugins

  • The role of widgets

The role of the WordPress theme

Many 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, but we can easily visualize the theme 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 for creating 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 the views.

The 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 a web-application-specific structure. Let's visualize the common layout of WordPress using the following diagram:

Having looked at the structure, it's obvious that the Header, Footer, and Main Content areas are mandatory even for web applications, but 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 that targets 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 super 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 process.

In situations where we need to provide dynamic layouts based on user types, devices, or browsers, we can dynamically switch between different themes by writing custom functions.

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 compared to other competitive frameworks. Most of you should be familiar with using the admin area for CMS functionalities, but we will have to understand how each component in the admin area suits the development of web applications.

Admin dashboard

The dashboard is the location where all the users get redirected, once they are logged in to the admin area. Usually it contains dynamic widget areas with the most important data of your application. The dashboard could play a major role in web applications, compared to blogging or CMS functionality. We can remove the existing widgets related to CMS and add application-specific widgets to create a powerful dashboard.

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, and Services.

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 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.

Settings

This section involves general application settings. Most of the prebuilt items in this section are suited to blogs and websites. We can customize this section to add new configuration areas related to our plugins that are 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 for adding new sections is one of the key reasons for its flexibility.

The role of plugins

In normal circumstances, WordPress developers use functions, which involve application logic scattered across theme files and plugins. Some developers even change the core files of WordPress, which is considered to be a very bad practice. In web applications, we need to be much more organized. In the section The role of the WordPress theme, 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. In short, anything you develop for web applications should go inside plugins, instead of theme files.

The plugin 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 that, 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 typical blogging or from a CMS user's perspective, it's a completely valid statement. In fact, widgets offer more in web applications by going beyond 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 the source code. The following screenshot shows a sample dynamic widgetized area. We can use the same technique to develop 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 the application that we will be developing throughout this book.

 

A development plan for a 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 are going to 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 of the goal of this application, and its features, functionalities, and the structure of components to see how it fits into WordPress.

Application goals and a target audience

Developers and designers who work online as freelancers know the importance of a personal profile to show your skills for an improved reputation. But most people, including experts who work full time jobs, don't maintain such profiles and hence remain 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 is aimed at those who are involved in web development and design. I believe that both the 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 screenshot shows the structure of our application's home page:

The backend will be developed by customizing the built-in admin module of WordPress. The 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. The following are the user roles and their respective functionalities:

  • Admin: This manages the application's configurations, settings, and the 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 plugins, themes, books, articles, and applications created by developers and designers. They will be able to access and download the work made public by developers. Basically, the members will have more permission to directly interact with developers, compared to subscribers. We could also implement a premium content section in the future for paid members.

  • Subscribers: This is also a normal user who wants to follow the activities of their preferred developers. These users will be notified whenever their preferred developers create a new activity within the 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 profiles by completing content divided into various sections such as services, portfolios, articles, and books.

  • 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.

  • Settings panel: A 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 a 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 Internet browsing using mobile devices, 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 this book, we will be creating functionalities such as open auth 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 have a look at various types of WordPress-powered web applications at http://www.innovativephp.com/demo/packt/wordpress_applications.

 

Understanding limitations and sticking with guidelines


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

In this section, we are going to 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 fit with your 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 could be a limitation in WordPress as it's built-in to work with the 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 are going to 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 an 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. 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 the 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 for updating 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 towards object-oriented architecture, so there will be a mix of both procedural and object-oriented codes. WordPress also uses hook-based architecture for providing 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 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 developers. Being human, we always prefer a practical approach to learning new things over the more conventional theoretical approach.

So, I am going to complete this chapter by converting the default WordPress functionality into a simple question-answer interface such as Stack Overflow, to show you a glimpse into what we are going to develop throughout this book.

Prerequisites

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

Also we will be using the TwentyTwelve theme, which is available with the default WordPress installation. Make sure to activate the TwentyTwelve 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 for each question

  • Customize the question list to include the 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, 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, the post can be considered as the question and the 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 in order to keep the default functionality of posts and let the new functionality be implemented separately without affecting the existing ones.

We are going to create a plugin to implement the necessary tasks for our application. First, create a folder called wpwa-questions inside the /wp-content/plugins folder and add a new file called index.php. Next, we need to add the block comment to define our file as a plugin:

/*
Plugin Name: WP 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
*/

Having created the main plugin file, we can move into creating a custom post type called wp_question using the following code snippet. Include the code snippet in your index.php file of the plugin:

add_action('init', 'register_wp_questions');

function register_wp_questions() {

  $labels = array(
    'name' => __( 'Questions', 'wp_question' ),
    'singular_name' => __( 'Question', 'wp_question' ),
    'add_new'  => __( 'Add New', 'wp_question' ),
    'add_new_item' => __( 'Add New Question', 'wp_question' ),
    'edit_item' => __( 'Edit Questions', 'wp_question' ),
    'new_item'  => __( 'New Question', 'wp_question' ),
    'view_item' => __( 'View Question', 'wp_question' ),
    'search_items' => __( 'Search Questions', 'wp_question' ),
    'not_found' => __( 'No Questions found', 'wp_question' ),
    'not_found_in_trash' => __( 'No Questions found in Trash', 'wp_question' ),
    'parent_item_colon' => __( 'Parent Question:', 'wp_question' ),
    'menu_name' => __( 'Questions', 'wp_question' ),
    );

  $args = array(
    'labels'  => $labels,
    'hierarchical' => true,
    'description' => __( 'Questions and Answers', 'wp_question' ),
    '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( 'wp_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 in 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 you have a look at the 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. It is considered bad practice as it becomes extremely difficult to maintain as 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 the later chapters.

Once the code is included, you will get a new section in the admin area for creating questions. Add a few questions and put some comments in using different users, before we move on to the next stage.

Changing the status of answers

Once users provide their answers, the creator of the question should be able to mark them as correct or incorrect. So, we are going to implement a button for each answer to mark its 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.

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 implement our own version of wp_list_comments using a custom function. First, you have to open the comments.php file of the theme and look for the call to the wp_list_comments function. You should see something similar to the following code:

<?php wp_list_comments( array( 'callback' => 'twentytwelve_comment', 'style' => 'ol' ) ); ?>

This function is used to generate a comments list for all types of posts, but we need a slightly modified version to suit the answers list. So we call the wp_list_comments function with different arguments, as shown in the following code:

<?php
if( get_post_type( $post ) == "wp_question" ){
wp_list_comments(  array( 'type' => 'comment', 'callback' => 'wpwa_comment_list', 'style' => 'ol' ) );
} else{

wp_list_comments(  array( 'type' => 'comment', 'callback' => 'twentytwelve_comment', 'style' => 'ol' ) );
}
?>

Note

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

Here we include a conditional check for the post type in order to choose the correct answer list generation function. When the post type is wp_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 the answers list.

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, so I'll just be explaining the important sections of the code. It's best to work with the full code for the wpwa_comment_list function from the source code folder. Have a look at the following code snippet:

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

}

wpwa_comment_list 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 only be visible to the creator of the question.

First, we 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. Next, we check whether the logged in user created the question. If so, we set the $show_answer_status variable to true. Also, we have to retrieve the status of the current answer by passing the comment ID and the _wpwa_answer_status key to the get_comment_meta function.

Then we will have to include the common code for generating the comments list with the necessary condition checks. Open the wpwa-questions.php file of the plugin and go through the rest of the wpwa_comment_list function to get an idea of how the comments loop works.

Next, we have to highlight the correct answers for 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>";
  }
?>

In the source code, you will see a DIV element with the class reply for creating the comment reply link. We need to insert our answer button status code right after that, 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';
    } else {
      $question_status = 'valid';
      $question_status_text = 'Mark as Correct';
    }

  ?>
  <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>

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 get the status of the answer as true or false using the _wpwa_answer_status key from the commentmeta table. Based on the returned value, we define buttons for either Mark as Incorrect or Mark as Correct. Also, we specify some CSS classes and HTML5 data attributes to be used later with jQuery. Finally, we keep the comment ID in a hidden variable called hcomment.

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

Next, we need to implement the AJAX request for marking the status of the answer as true or false. Before that, 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( 'wp-questions', plugins_url( 'js/questions.js', __FILE__ ), array('jquery'), '1.0',true );
  wp_enqueue_script( 'wp-questions' );

  wp_register_style( 'questions', plugins_url( 'css/questions.css', __FILE__ ) );
  wp_enqueue_style( 'questions' );

  $config_array = array(
    'ajaxURL' => admin_url( 'admin-ajax.php' ),
    'ajaxNonce' => wp_create_nonce( 'ques-nonce' )
  );

  wp_localize_script( 'wp-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. wp_enqueue_script is used to include script files into the page while wp_register_script is used to add custom files. Since jQuery is built into WordPress, we can just use wp_enqueue_script 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 parameter 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. Now everything is set up properly to create the AJAX request.

Saving the status of answers

Once the author clicks on 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.

$jq =jQuery.noConflict();

$jq(document).ready( function() {

  $jq(".answer-status").click( function() {

    // Get the button object and current status of the answer
    var answer_button = $jq(this);
    var answer_status  = $jq(this).attr("data-ques-status");

    // Get the ID of the clicked answer using hidden field
    var comment_id = $jq(this).parent().find(".hcomment").val();
    var data = {
      "comment_id":comment_id,
      "status": answer_status
    };

    // Create the AJAX request to save the status to database
    $jq.post( wpwaconf.ajaxURL, {
      action:"mark_answer_status",
      nonce:wpwaconf.ajaxNonce,
      data : data,
    }, function( data ) {
      if("success" == data.status){
      /*Changes the display text of answer status button and toggles the answer status between valid and invalid to be displayed in frontend.*/
        if("valid" == answer_status){
          $jq(answer_button).val("Mark as Incorrect");
          $jq(answer_button).attr("data-ques-status","invalid");
        }else{
          $jq(answer_button).val("Mark as Correct");
          $jq(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.

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

The next step of this process is to implement the server-side code for handling AJAX requests. 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 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 of 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.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Generating the 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. In this file we are going to create a customized layout for our questions. Make a copy of the existing archive.php file of the TwentyTwelve theme and rename it archive-wp_question.php. In this file, you will find the following code section:

get_template_part( 'content', get_post_format() );

The TwentyTwelve 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 custom templates called content-questions.php by duplicating the content.php file and change the preceding code to the following:

get_template_part( 'content-questions', get_post_format() );

Finally, we need to consider the implementation of the content-questions.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 functions the_excerpt and the_content in the template.

Then we also have to remove the twentytwelve_entry_meta function and create our own metadata using the following code:

<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. Then we need to display the number of correct answers for 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 for retrieving the approved answers of each post, which also 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 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 the HTML and PHP code inside both themes and plugins.

Note

I suggest you go through the Chapter 1 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 be developing a web application from scratch using detailed explanation in the upcoming chapters.

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

 

Summary


Our main goal was to find out 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 modules of WordPress and how each of these 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 the existing functionalities.

By now, you should know how to:

  • Decide whether to choose WordPress for your web application

  • Visualize how your requirements fit into the components of WordPress

  • Identify and minimize the limitations

In the next chapter, we are going to start the development of the portfolio management application with the user module. Before we go there, I suggest you do some research on user management modules 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. Rakhitha is the creator of WPExpertDeveloper, where he shares his latest WordPress plugins. 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
Book Title
Unlock this full book FREE 10 day trial
Start Free Trial