Application Framework - Professional WordPress: Design and Development, 3rd Edition (2015)

Professional WordPress: Design and Development, 3rd Edition (2015)

Chapter 14. Application Framework

WHAT’S IN THIS CHAPTER?

· Understanding an application framework

· Reviewing application framework features

· Using WordPress as an application framework

· Common WordPress framework features

Over the years WordPress has grown from a simple blogging platform to a full-fledged content management system. In the past few years, a new trend has emerged—using WordPress as an application framework. Matt Mullenweg, the co-founding developer of WordPress, has often referred to WordPress as a web operating system. With that in mind, it’s important we stop thinking of WordPress as a specific type of platform, but rather a framework that can be used to build any type of web application imaginable.

This chapter reviews what an application framework is and how you can leverage WordPress to create amazing web applications.

WHAT IS AN APPLICATION FRAMEWORK?

An application framework consists of a software framework used by software developers to implement the standard structure of an application. More simply, a framework consists of a set of conventions used to easily build applications for the web.

For example, let’s assume you are going to build a customer relationship management (CRM) application. Your application would require a database abstraction layer for storing and retrieving the data from your CRM. Your application would also require an application layer with flexibility to extend the framework to fit your CRM application’s requirements. The final piece would be the presentation layer, which would handle the display of your CRM. Does this sound familiar? It should, because it sounds just like WordPress!

WordPress as an Application Framework

Now that you understand what an application framework is, let’s examine how WordPress can be used as a framework for your web applications.

Let’s review some standard application framework features:

· User management

· Template engine

· Error logging

· Localization

· Form and data validation

· Uploads and media management

· Image manipulation

· Scheduled tasks

· Friendly URLs

· External APIs

· Caching

· Flexible

This is not an exhaustive list, but some of the more popular framework features offered by most application frameworks. This list of features should look very familiar because this is also a list of WordPress features available for use in your applications.

Now let’s dig into a few of the more popular framework features and how they relate in WordPress.

User Management

If you have ever logged in to a WordPress website, you have interacted with the WordPress user management system. WordPress, by default, creates five user roles:

· Subscriber

· Contributor

· Author

· Editor

· Administrator

As discussed in Chapters 12 and 13, user roles in WordPress can be easily extended to include custom roles and capabilities. In the case of your CRM application example, you may want to define a custom user role that can only view customer information. You may also want to define a role for a user so he or she can view and modify customer information.

User capabilities are also a very important part of user management in WordPress. A capability gives the user role a very specific action the user can perform. For example, there is a capability for publishing a new post. User roles and capabilities are not only used for granting permissions, but can also be used to restrict access to various parts of your application.

Let’s register a user role for customers in your CRM. This role will be assigned to any customers that are allowed to log in to your CRM application.

<?php

register_activation_hook( __FILE__, 'prowp_create_role_on_activation' );

function prowp_create_role_on_activation() {

//register new customer role

add_role(

'customer',

'Customer',

array(

'read' => true,

'edit_posts' => true,

'delete_posts' => false,

)

);

}

?>

When registering a new role, the new role is stored in the WordPress options table. Because of this, there’s no reason to run your code on every page load. Instead, you’ll use the register_activation_hook() function to register the customer user role when your plugin is activated.

Next, you’ll use the add_role() function to define your new customer role. The first parameter is the user role name. The second parameter is the user role display name. The final parameters are the capabilities for the user role, which accepts an array of capability names. In this example, you are assigning your customer user role with permissions to read and edit posts, but not to delete posts. If you wanted even more granular user control, you could register custom capabilities that only customer user roles would use.

Now that you have a customer user role, let’s look at creating a new user with that role. If you are building a web application, you will probably want to provide the user the ability to create a new user account in your application. Let’s assume you have a registration form that accepts an email address.

<?php

if ( null == username_exists( $email_address ) ) {

// generate a password and create the user

$password = wp_generate_password( 12, false );

$user_id = wp_create_user( $email_address, $password, $email_address );

// set the user role to customer

$user = new WP_User( $user_id );

$user->set_role( 'customer' );

} else {

// user already exists

}

?>

The preceding example accepts an $email_address variable containing the new user’s email when registering. First, you’ll use the username_exists() function to verify that the email address is not already in use by another user. Next, you’ll generate a random password using wp_generate_password(). Now that you have the user’s email and a random password, it’s time to create the user with the wp_create_user() function.

The final step is to set the user’s role. First, you’ll create a new instance of WP_User from the $user_id variable that was set when the new user was created. To set the role, you’ll call the set_role() function and set the role to customer. You now have a new user created, with their user role set to customer, who can log into your web application in WordPress.

User accounts are a main component for most web applications and WordPress makes working with users incredibly flexible. Because of this flexibility, you can easily customize your setup to fit any application you are creating using WordPress.

Template Engine

The WordPress template engine will power the presentation layer of your application. In Chapter 9, you learned how to create custom theme templates for WordPress. As discussed, WordPress has a very flexible template engine, allowing you to create any number of customized templates for your applications.

Using the CRM example, you may need public facing templates to accept new customer leads, register user accounts, allow customers to manage their accounts, and more. For your applications, anything that deals with the public facing display will use WordPress theme templates.

WordPress themes can also be used for administrative interfaces. Rather than trying to customize the default WordPress admin dashboard, it can be a much easier approach to create a custom admin only theme. This theme could give your users all of the admin features they need and nothing more. You won’t need to worry about hiding default WordPress admin features you don’t want your users having access to because the admin theme will only have the features you introduce in it.

For more information on templates in WordPress, visit the Codex at http://codex.wordpress.org/Templates.

CRUD

CRUD, or “Create, Read, Update, and Delete,” is a basic function of persistent storage in programming. A web application framework will include help for performing these basic operations, and WordPress is no different.

WordPress not only provides CRUD out of the box, but automatically handles the CRUD operations for all of your custom post types. Let’s look at an example registering a custom post type for the customers in your CRM:

<?php

add_action( 'init', 'prowp_create_post_type' );

function prowp_create_post_type() {

register_post_type( 'customer',

array(

'labels' => array(

'name' => 'Customers',

'singular_name' => 'Customer'

),

'public' => true,

'has_archive' => true,

)

);

}

?>

Now that your post type is registered, you have full CRUD integration automatically in WordPress. You can easily create customer entries (C), read entries (R), update existing entries (U), and delete entries (D). This is a very simple example that demos some very powerful tools at your disposal with a few lines of code.

WordPress includes a set of functions for CRUD operations related to settings, post content, users, metadata, and more. Let’s review the CRUD functions for these operations:

Settings

CRUD operation functions for Settings in WordPress are:

· add_option()—Create a new option (C).

· get_option()—Retrieve an options value (R).

· update_option()—Update an existing option (U).

· delete_option()—Delete an option (D).

Posts

CRUD operation functions for Posts in WordPress are:

· wp_insert_post()—Create a new post (C).

· get_post() – Retrieve a post (R).

· wp_update_post()—Update an existing post (U).

· wp_delete_post()—Delete a post (D).

Post Metadata

CRUD operation functions for Post metadata in WordPress are:

· add_post_meta()—Create new post metadata (C).

· get_post_meta()—Retrieve post metadata (R).

· update_post_meta()—Update existing post metadata (U).

· delete_post_meta()—Delete post metadata (D).

Users

CRUD operation functions for Users in WordPress are:

· wp_create_user()—Create a new user (C).

· get_userdata()—Retrieve a user’s data (R).

· wp_update_user()—Update an existing user (U).

· wp_delete_user()—Delete a user (D).

Any web application that you create will have some type of CRUD operations. WordPress includes the functions needed to make storing, retrieving, updating, and deleting data in your web applications a breeze.

Caching

WordPress features a simple-to-use cache layer for your applications. Not all applications require data caching, but caching should always be used to cache data that may be computationally expensive to regenerate. For example, a complex database’s query results should be cached on initial load and only refreshed if parameters require it. There are two APIs available in WordPress for caching: Cache API and Transient API.

The Cache API allows you to store data in a cache that resides in memory only for the duration of the request. That means, cached data is not stored persistently across page loads with the use of a persistent caching plugin. The Cache API features a few different functions:

· wp_cache_add()—Adds data to the cache key if it doesn’t already exist. If data already exists for the key, the data will not be added and the function will return false.

· wp_cache_set()—Adds data to the cache key. If the key already exists, the data will be overwritten; if not, the cache will be created.

· wp_cache_get()—Returns the value of the cached object.

· wp_cache_delete()—Clears data from the cache for the given key.

· wp_cache_replace()—Replaces the cache for a given key if it exists; returns false otherwise.

· wp_cache_flush()—Clears all cached data.

Let’s review a simple example of working with cached data:

<?php

//load the cache value if it exists

$result = wp_cache_get( 'prowp_cached_data' );

if ( false === $result ) {

$result = $wpdb->get_results( $query );

wp_cache_set( 'prowp_cached_data', $result );

}

// do something with $result

?>

In the preceding example, you’re using the wp_cache_get() function to retrieve the cached data to the $result variable. If $result is empty, meaning there is no cached data, you generate the data for the cache. Once the $result variable has a value, you’ll use thewp_cache_set() function to save the cached data. After the code has been executed, the $result variable will contain the cached data from your custom $wpdb query.

For more information on the WordPress Cache API visit the Codex at http://codex.wordpress.org/Class_Reference/WP_Object_Cache.

The Transient API allows you to cache data in the database and expire that data at a specific date and time. Because the data stored via the Transient API is saved in the database, it is available across your entire application. The Transient API functions are very similar to the Cache API, with the addition of an $expiration parameter:

<?php

//load the transient value if it exists

$result = get_transient( 'prowp_cached_data' );

if ( false === $result ) {

$result = $wpdb->get_results( $query );

set_transient( 'prowp_cached_data', $result, 12 * HOUR_IN_SECONDS );

}

// do something with $result

?>

As you can see, the preceding example is very similar to the Cache API example. The only difference is you are using the get_transient() and set_transient() functions and setting an expiration time for the cached data. The expiration time is using a WordPress constant that returns the number of seconds in an hour, so in this example the expiration time is set to 1 year.

For more information on the Transient API, visit the Codex at http://codex.wordpress.org/Transients_API.

Friendly URLs

A web application’s URL structure can be a very important feature of your application. Keyword injected URLs, or permalinks as they are known in WordPress, are a common feature on the Internet today. Rather than having URLs that contain confusing query strings (http://example.com/?ID=54), friendly URLs contain meaningful terms in the URL structure (http://example.com/join).

It’s important to understand how the Rewrite API works in WordPress. It breaks down to a four-step process:

1. A URL is requested from the web server.

2. If a physical file exists, it will be returned (images, fonts, and so on).

3. If a physical file does not exist, the request will be directed to index.php.

4. The content will be returned from WordPress.

When visiting http://example.com/join, WordPress will take the join slug, query the database for the content, and return the join page content to the visitor.

The default WordPress permalink feature is a very powerful and easy-to-configure option for defining your permalink settings. You can adjust the default permalink settings in the Permalink Screen of the WordPress dashboard.

WordPress features a Rewrite API that enables you to customize your URL structure to fit your application requirements exactly. This API will help you go beyond the permalink settings in WordPress and programmatically build custom rewrite rules for your URLs. The Rewrite API is one of the more advanced WordPress APIs available, so it’s important to always test your rewrite code logic in a development or staging environment prior to deploying to a live website.

For more information on the Rewrite API, visit the Codex at http://codex.wordpress.org/Rewrite_API.

External APIs

WordPress features two primary external APIs: XML-RPC and the REST API. These APIs can be used to interact with your web application externally. For example, you could create a native iOS application to view and update entries in your CRM application using one of these APIs.

The WordPress XML-RPC is the older of the two APIs and has been in WordPress core for a long time. Currently, all of the WordPress mobile apps utilize the XML-RPC API to post and pull content from WordPress remotely. This API also handles authentication when logging into your WordPress site through the API.

The REST API is the newest WordPress API on the block. You can install the JSON REST API plugin located at https://wordpress.org/plugins/json-rest-api/. The REST API is a powerful tool that allows you to get your site’s data in simple JSON format, including posts, taxonomies, and more. Retrieving and updating data via this API is as simple as sending an HTTP request. There are plans for the REST API to be included in the core of WordPress, but for now it lives in a plugin.

The WordPress REST API has an extensive documentation website for learning how to interact with the API. You can view the documentation at http://wp-api.org/.

Uploads and Media Management

Requirements for any web application are file upload and media management capabilities. These could be as simple as uploading a custom user avatar or as complex as a document file management system.

When discussing media management in WordPress, we’re not just talking about images and videos. Media can include any type of file, including documents, spreadsheets, PDFs, executables, or any other type of file you’d like to use. WordPress features a robust media management system that will work with any files your application requires.

WordPress also features some advanced image operations for cropping, flipping, and resizing uploaded images. Image gallery support is a default feature in WordPress, making it very easy for uploaded images to be displayed in a gallery layout.

All of these media tools are available for use in your web applications.

Scheduled Tasks

As you work to build more complex web applications, you will no doubt need the ability to run tasks on a schedule. For example, your CRM application may send a weekly digest email of all newly registered users in your app.

WordPress features a cron system for executing tasks on a schedule. You can easily schedule a function to execute at a specific recurring interval or to only run once and never again. Let’s look at an example using the WordPress Cron API to send an hourly email reminding us to stay awake:

<?php

register_activation_hook( __FILE__, 'prowp_cron_schedule' );

function prowp_cron_schedule() {

//verify event has not been scheduled

if ( ! wp_next_scheduled( 'prowp_cron_hook' ) ) {

//schedule the event to run hourly

wp_schedule_event( time(), 'hourly', 'prowp_cron_hook' );

}

}

add_action( 'prowp_cron_hook', 'prowp_cron_email_reminder' );

function prowp_cron_email_reminder() {

//send scheduled email

wp_mail( 'brad@webdevstudios.com', 'Elm St. Reminder', 'Don\'t fall asleep!' );

}

?>

You’ll use the register_activation_hook() to register your cron task. In this example, the cron schedule will be set when the plugin is activated. The first thing to do is verify the cron task is not already scheduled, which you’ll check using the wp_next_scheduled()function.

After you verify the cron task has not been scheduled, it’s time to schedule the task using the wp_schedule_event() function. The first parameter is the time you want the cron task to run initially. Setting that parameter to time() will set it to the current local time configured in WordPress. Next you’ll set the recurrence, or how often the event should reoccur. In this example, you want the email to send every hour, so you’ll set that value to hourly. The final parameter is the hook you want to trigger when the cron schedule runs.

Now that the cron job is scheduled, you need to actually tell cron what you are wanting to do. To start, you’ll register a new action hook called prowp_cron_hook, which is the hook parameter you passed when scheduling the cron job. This hook will execute yourprowp_cron_email_reminder() function, which uses wp_mail() to send out your email reminder. That’s it! You have now scheduled an hourly email to remind you to stay awake.

This is a pretty basic example of scheduled cron jobs in WordPress, but it does highlight how powerful this feature can be. You can schedule custom cron jobs for any number of tasks including different recurrence settings, whether it be monthly, weekly, daily, hourly, or even by the minute.

Flexibility

As you’ve learned throughout this book, WordPress is an endlessly flexible platform that can be customized to build any website imaginable. The extensibility within WordPress is one of the major reasons that WordPress has become so popular over the years. WordPress core includes over 2,000 hooks available to modify every component and feature within WordPress.

Beyond the WordPress core, over 34,000 plugins are freely available in the WordPress.org Plugin Directory. The saying “There’s a plugin for that” rings very true when searching through the Plugin Directory. When you need the ability to introduce a new feature for your web app, chances are there is a plugin for that, which will ultimately save you time and money.

There are also nearly 3,000 free themes available in the WordPress.org Themes Directory. Aside from designing and building a custom theme, there’s no need to start your web apps design from scratch. There are thousands of free options that can serve as a starting point for your web application.

Beyond WordPress.org, thousands of resources are available online including shared code on Github and Bitbucket, tutorials and demos, documentation, and more to help you extend WordPress when developing your web applications.

SUMMARY

The primary reason to use an application framework is to make the project quicker to complete and maintenance easier. As a WordPress developer, you are already working with WordPress regularly, which gives you the added bonus of working with a framework you already understand.

It’s clear that WordPress is perfectly capable of being an application framework for your web apps. With its robust APIs, large featureset, extensibility, and ongoing active development, WordPress can rival some of the best frameworks out there.