Chapter 1. Building Web Apps with WordPress

This book will help you build anything with WordPress: websites, themes, plugins, web services, and web apps. We chose to focus on web apps because you can view them as super websites that make use of all of the techniques we will cover.

There are many people who believe that WordPress isn’t powerful enough or meant for building web apps; we’ll get into that more later on. We’ve been building web apps with WordPress for many years and know that it’s absolutely possible for you to use it to build scalable applications.

In this chapter, we start by defining what web app’s are and then cover why WordPress is a great framework for building them. We also describe some situations in which using WordPress wouldn’t be the best way to build your web app.

What Is an App?

We like the Wikipedia definition: “Application software (app for short) is software designed to perform a group of coordinated functions, tasks, or activities for the benefit of the user.”

What Is a Web App?

A web app is just an app run through a web browser.

Note that with some web apps, the browser technology is hidden—for example, when you’re integrating your web app into a native Android or iOS app, running a website as an application in Google Chrome, or running an app using Adobe AIR. However, inside these applications, there is still a system parsing HTML, CSS, and JavaScript.

You can also think of a web app as a website, plus more application-like stuff. There is no exact dividing line where a website becomes a web app. It’s one of those cases where you just know it when you see it.

What we can do is explain some of the features of a web app, give you some examples, and then try to come up with a shorthand definition so that you know generally what we are talking about as we use the term throughout the book.

Features of a Web App

The following are some features typically associated with web apps and applications in general. The more of these features there are in a website, the more appropriate it is to upgrade its label to a web app.1

Interactive elements

A typical website experience involves navigating through page loads, scrolling, and clicking hyperlinks. Web apps can have links and scrolling, too, but they tend to use other methods of navigating through the app.

Websites with forms offer transactional experiences. An example would be a contact form on a website or an application form on the careers page of a company’s career website. Forms allow users to interact with a site using something more than a click.

Web apps will have even more interactive user interface (UI) elements. Examples include toolbars, drag-and-drop elements, rich text editors, and sliders.

Tasks rather than content

Remember, web apps are “designed to help the user to perform specific tasks.” Google Maps users get driving directions. Gmail users write emails. Trello users manage lists. SchoolPress users comment on class discussions.

Some apps are still content focused. A typical session with a Facebook or Twitter app involves about 90% reading. However, the apps themselves present a way of browsing content different from the typical web browsing experience.

Logins

Logins and accounts allow a web app to save information about its users. This information is used to facilitate the main tasks of the app and enable a persistent experience. When logged in, SchoolPress users can see which discussions are unread. They also have a username that identifies their activity within the app.

Web apps can also have tiers of users. SchoolPress will have administrators controlling the inner workings of the app, teachers setting up classes, and students participating in class discussions.

Device capabilities

Web apps running on your phone can access your camera, your address book, internal storage, and GPS location information. Web apps running on the desktop may access a webcam or a local hard drive. The same web app might respond differently depending on the device accessing it. Web apps will adjust to different screen sizes, resolutions, and capabilities.

Work offline

Whenever possible, it’s a good idea to make your web apps work offline. Sure, the interactivity of the internet is what defines that “web” part of web app, but a site that still works when you drive through a tunnel will feel more like an app.

With Gmail, you can draft emails offline. Evernote allows you to draft notes offline and then synchronize them to the internet when connectivity is restored.

Mashups

Web apps can tie one or more web apps together. A web app can utilize various web services and APIs to push and pull data. You could have a web app that pulls location-based information like longitude and latitude from Twitter and Foursquare and posts it to a Google Map.

Mobile Apps

Since the first edition of this book was published back in 2012, web apps—and mobile apps in particular—have taken off. On most websites, mobile devices have now overtaken desktop computers as the largest source of traffic (Source: Perficient, Inc.).

In 2012, the quintessential web app looked something like Basecamp, project management software accessed through your desktop web browser. In 2019, the quintessential web app looks like Twitter, a communication app accessed through your iOS or Android phone.

Because in most cases, the majority of your users will be accessing your websites and apps on a mobile device, we support a “mobile first” mindset when designing and developing web apps. We cover how to get your WordPress apps running natively on mobile in Chapter 16. We cover the basics of responsive design and having your websites show up properly for any screen size in Chapter 4.

Progressive Web Apps

Progressive web apps (PWAs) are websites that take advantage of modern browser features to behave as native apps in Android, iOS, or on the desktop. Specifically, websites that use service workers to function while offline have a web app manifest file to define the app to the operating system (OS), and meet a few other requirements so they can be launched as apps directly from the browser.

PWAs have been championed by the Google Chrome team, but are now supported on iOS and most modern web browsers. A feature plugin for PWA support is in development to support the primary features of PWAs in WordPress core. You can use this plugin turn your WordPress site into a PWA, and that is a good idea, but in reality coding a PWA is more of a mindset than a simple conversion. Similar to the “features of a web app” we just described, the main PWA site at Google has a checklist of features expected for most PWAs, including these baseline features:

  • Site is served over HTTPS.

  • Pages are responsive on tablets and mobile devices.

  • All app URLs load while offline.

  • Metadata is provided for Add to Home screen.

  • First load is fast even on 3G.

  • Site works cross-browser.

  • Page transitions don’t feel like they block on the network.

  • Each page has a URL.

In addition to the baseline features, there is a checklist of items for “exemplary” PWAs that covers user experience (UX) and performance. Google’s Lighthouse tool provides automated tests and reports for meeting the PWA criteria. Even fully native apps or apps built for the browser can benefit from some of the suggestions in the PWA checklists and Lighthouse reports.

Why Use WordPress?

No single programming language or software tool will be right for every job. We’ll explore why you may not want to use WordPress in a bit, but for now, let’s go over some situations in which using WordPress to build your web app would be a good choice.

Content Management Is Easy with WordPress

Developed first as a blogging platform, WordPress has evolved through the years, and with the introduction of custom post types (CPTs) in version 3.0, into a fully functional content management system (CMS). Any page or post can be edited by administrators via the dashboard, which can be accessed through your web browser. You will learn about working with CPTs in Chapter 5.

WordPress makes adding and editing content easy via a WYSIWYG (What You See Is What You Get) editor, so you don’t have to use web designers every time you want to make a simple change to your site. You can also create custom menus and navigation elements for your site without touching any code.

If your web app focuses on bits of content (e.g., our SchoolPress app is focused on assignments and discussions), the Custom Post Types API for WordPress (covered in Chapter 5) makes it easy to quickly set up and manage this custom content.

Even apps that are more task oriented will typically have a few pages for information, documentation, and sales. Using WordPress for your app will give you one place to manage your app and all of your content.

Cost

WordPress is free. PHP is free. MySQL is free. Most plugins are free.

Servers and hosting cost money, but depending on how big your web application is and how much traffic you get, it can be relatively inexpensive. If you require custom functionality not found in any existing plugins, you may need to pay a developer to build it. Or if you are a developer yourself, it will cost you some time.

Responses to Some Common Criticisms of WordPress

Some highly vocal critics of WordPress might say that it isn’t a good framework for building web apps, or that it isn’t a framework at all. With all due respect to those with these opinions, we’d like to go over why we disagree. The following are some common criticisms.

WordPress plugins are crap

The Plugin API in WordPress and the thousands of plugins that have been developed using it are the secret sauce and, in our opinion, the number-one reason that WordPress has become so popular and is so successful as a website platform.

Some people will say, “Sure, there are thousands of plugins, but they are all crap.” OK, some of the plugins out there are crap.

But there are a lot of plugins that are most definitely not crap—among them, AppPresser, developed by coauthor Brian Messenlehner. If you like using WordPress to manage your written content or ecommerce store, the AppPresser plugin and platform is the fastest way to get that content or store into a mobile app.

Paid Memberships Pro, developed by coauthor Jason Coleman, is also not crap. Using Paid Memberships Pro to handle your member billing and management will allow you to focus your development efforts on your app’s core competency instead of how to integrate your site with a payment gateway.

A lot of plugins do something very simple (e.g., hiding the admin bar from nonadmins), work exactly as advertised, and don’t really have room for being crap.

Themes and plugins found in the WordPress.org repository are heavily vetted by volunteers for security and code quality. The WordPress.org Theme Review process is notoriously stricter and more comprehensive than processes at other marketplaces. The Tide project is working to add automated tests to the plugin and theme repositories that will result in higher-quality plugins and updates while also detecting compatibility and security issues faster.

Even the crappy plugins can be fixed, rewritten, or borrowed from to work better. You may find it easier sometimes to rewrite a bad plugin instead of fixing it. However, you are still further ahead than you would be if you had to write everything yourself from scratch.

No one is forcing you to use WordPress plugins without vetting them yourself. If you are building a serious web app, you’re going to check out the plugin code yourself, fix it up to meet your standards, and move on with development.

When Not to Use WordPress

WordPress isn’t the solution for every application. This section describes a few cases in which you wouldn’t want to use WordPress to build your application.

Another Platform Will Get You “There” Faster

If you have a team of experienced Ruby developers, you should use Ruby to build your web app. If there is a platform, framework, or bundle that includes 80% of the features you need for your web app and WordPress doesn’t have anything similar, you should probably use that other platform.

WordPress as an Application Framework

Content management systems like WordPress, Drupal, and Joomla are often left out of the framework discussion, but in reality, WordPress (in particular) is really great for what frameworks are supposed to be about: quickly building applications.

Within minutes, you can set up WordPress and have a fully functional app with user signups, session management, content management, and a dashboard to monitor site activity.

The various APIs, common objects, and helper functions covered throughout this book allow you to code complex applications faster without having to worry about lower-level systems integration.

Figure 1-2 shows that righthand triangle from Mullenweg’s 2013 “State of WordPress” presentation depicting a stable WordPress platform with a CMS layer built on top and a blogging application built on top of the CMS layer.

The reality is that the majority of the current WordPress codebase supports the underlying application platform. Think of each WordPress release as an application framework bundled with a sample blogging app.

Figure 1.2 The WordPress Platform
Figure 1-2. The WordPress platform

WordPress Versus Model-View-Controller Frameworks

Model-view-controller (MVC) is a common design pattern used in many software development frameworks. The main benefits of using an MVC architecture are code reusability and separation of concerns (SoC). WordPress doesn’t use an MVC architecture, but does in its own way encourage code reuse and SoC.

Here, we’ll briefly explain the MVC architecture, and how it maps to a WordPress development process. If you’re familiar with MVC-based frameworks, this section should help you understand how to approach WordPress development in a similar way.

Figure 1-3 describes a typical MVC-based application. The end user uses a controller, which manipulates the application state and data via a model, which then updates a view that is shown to the user. For example, in a blog application, a user might be looking at the recent posts page (a view). The user would click a post title, which would take the user to a new URL (a controller) that would load the post data (in a model) and display the single post (a different view).

How MVC works.
Figure 1-3. How MVC works

The MVC architecture supports code reusability by allowing the models, views, and controllers to interact. For example, both the recent posts view and the single posts view might use the same post model when displaying post data. The same models might be used in the frontend to display posts and in the backend to edit them. The MVC architecture supports SoC by allowing designers to focus their attention on the views while programmers focus their attention on the models.

You could try to use an MVC architecture within WordPress. There are a number of projects to help you do just that; however, we think trying to strap MVC onto WordPress could lead to issues unless the WordPress core were to officially support MVC. Instead, we suggest following the “WordPress Way,” as outlined in this book.

Still, if you are interested, the WP MVC plugin is in active development and helps you to use an MVC framework to create WordPress plugins. If you don’t want or need to go full MVC, there are a couple of ways to map an MVC process to WordPress.

Views = themes

In an MVC framework, the code to display data to the user is written in the views. This is where designers and frontend developers will spend the majority of their time.

In WordPress, themes are the proper place to store templating code and logic.

Again, the comparison here doesn’t map one to one, but “views = themes” is a good starting point.

Anatomy of a WordPress App

In this section, we describe the app we built as a companion for this book: SchoolPress. We’ll cover the intended functionality of SchoolPress, how it works and who will use it, and—most important for this book—how each piece of the app is built in WordPress.

Don’t be alarmed if you don’t understand some of the following terminology. In later chapters, we review everything introduced here in more detail. Whenever possible, we point to the chapter that corresponds to the feature discussed.

Note

This book is not meant to be a “how to re-create the SchoolPress app” book or step-by-step walkthrough guide. When it makes sense, we use SchoolPress in our code examples throughout the book so you don’t have to spend time understanding the context of every individual example.

Membership Levels and User Roles

Teachers are given a Teacher membership level (through Paid Memberships Pro) and a custom role called “Teacher” that gives them access to create and edit their classes, moderate discussions in their class forums, and create and manage assignments for their classes.

Teachers do not have access to the WordPress dashboard. They create and manage their classes and assignments through frontend forms created for this purpose.

Students are given a “Student” membership level and the default “Subscriber” role in WordPress. Students have access to view and participate only in classes to which they are invited by their teachers. Details on user roles and capabilities are explained in Chapter 6, and Chapter 15 covers using membership levels to control access.

Classes Are BuddyPress Groups

When teachers create “classes,” they are really creating BuddyPress groups and inviting their students to the group. Using BuddyPress, we get class forums, private messaging, and a nice way to organize our users.

The class discussion forums are powered by the bbPress plugin. A new forum is generated for each class, and BuddyPress manages access to the forums. Details on leveraging third-party plugins like BuddyPress and bbPress can be found in Chapter 3.

Submissions Are a (Sub)CPT for Assignments

Students can post comments on an assignment, and they can also choose to post their official submission for the assignment through another form on the frontend.

Submissions, like assignments, are also CPTs. Submissions are linked to assignments by setting the submission’s post_parent field to the ID of the assignment to which it was submitted. Students can post text content and also add one or more attachments to a submission.

Semesters Are a Taxonomy on the Class CPT

A custom taxonomy called Semester is set up for the group/class CPT. School admins can add new semesters to their sites. For example, a “fall 2019” semester could be created and teachers could assign this semester when creating their classes. Students then can easily browse a list of all fall 2019 classes.

Departments Are a Taxonomy on the Class CPT

A custom taxonomy called Department is also set up for the group/class CPT. This is also available as a drop-down list for teachers when creating their classes, and allows students to browse the list of classes by department.

SchoolPress Has One Main Custom Plugin

Behind the scenes, the custom bits of the SchoolPress app are controlled from a single custom plugin called SchoolPress. This—the main plugin—includes definitions for the various CPTs, taxonomies, and user roles. It also contains the code to tweak the third-party plugins SchoolPress uses like Paid Memberships Pro and BuddyPress.

The main plugin also contains classes for school admins, teachers, and students that extend the WP_User class and classes for classes, assignments, and submissions that wrap the WP_Post class. These (PHP) classes allow us to organize our code in an object-oriented way that makes it easier to control how our various customizations work together and to extend our code in the future. These classes are fun to work with and allow for the code shown in Example 1-1.

Example 1-1. Possible user login events
if($class->isTeacher($current_user))
{
   //this is the teacher, show them teacher stuff
   //...
}
elseif($class->isStudent($current_user))
{
    //this is a student in the class, show them student stuff
    //...
}
elseif(is_user_logged_in())
{
    //not logged in, send them to the login form with a redirect back here
    wp_redirect(wp_login_url(get_permalink($class->ID)));
    exit;
}
else
{
    //not a member of this class, redirect them to the invite page
    wp_redirect($class->invite_url);
    exit;
}

Creating custom plugins is covered in Chapter 3, and extending the WP_User class in Chapter 6.

SchoolPress Uses a Few Other Custom Plugins

Occasionally, a bit of code will be developed for a particular app that would also be useful on other projects. If the code can be contained enough that it can run outside of the context of the current app and main plugin, it can be built into a separate custom plugin.

An example of this would be the Force First and Last Name as Display Name plugin that was a requirement for this project. It didn’t require any of the main plugin code to run and is useful for other WordPress sites outside of the context of the SchoolPress app. We created a separate plugin for this functionality and maintain it in the WordPress.org repository so others can use it and benefit from it.

SchoolPress Uses the Memberlite Theme

The main schoolpress.me site runs on a customized Memberlite child theme. If a school admin signs up for a premium subdomain, they can choose from a variety of Memberlite child themes; they can also change any of the theme’s colors, fonts, and logos to better fit school/class branding. Also, all themes use a responsive design that ensures the site will look good on mobile and tablet displays as well as desktop displays.

The code in the Memberlite theme is very strictly limited to display-related programming. The theme code obviously includes the HTML and CSS for the site’s layout, but also contains some simple logic that integrates with the main SchoolPress plugin (like the preceding branching code). However, any piece of code that manipulates the custom post types or user roles or involves a lot of calculation is delegated to the SchoolPress plugin.

Now that we’ve established what an app is, discussed why you might want to build one with WordPress, presented the “WordPress” way of separating concerns, and described at a high level our SchoolPress example app, let’s dig into the core of WordPress, what’s included, and how it works.

1 Many of the ideas in this section are influenced by the following blog posts: “What is a Web Application?” by Dominique Hazaël-Massieux, and “What is a Web Application?” by Bob Baxley.

2 W3Tech has regular surveys on the use of different content management systems.

3 Yii is an MVC-based PHP framework. Other PHP frameworks, like Laravel, are more popular among WordPress developers and the PHP community in general, but the MVC-related documentation on the Yii website is particularly well written.