Creative Coding

Using WordPress For Web Application Development: Available Features, Part 5 - Retrieving Data


By now, you know that the purpose of this series is to demonstrate how WordPress can be used as a foundation for web application development.

We started by taking a high-level look at many web application design patterns, how WordPress differs, and why WordPress should be considered to be more of a foundation rather than a framework.

Over the past few articles, we've taken a look at user roles, permissions, session management, email, and data serialization. But if you're going to be saving data to the database, it only makes sense that you're going to be retrieving it, right?

Luckily, the APIs that WordPress has available make it really easy to retrieve information from the database. On top of that, if you found the last article easy to follow, then you should have no problem following along with this article as many of the principles are the same:

  • We retrieve the information from the database using the unique ID we supplied when saving the information
  • We escape the data to make sure it's safe to render to the browser
  • We then return it to the calling function

Nothing terribly complicated, right?

And it really isn't—especially as it relates to leveraging the very same APIs (albeit different functions) that we used for saving information to the options table and the meta data tables. In this article, we're going to continue our discussion on how to retrieve information, as well as how to make sure we're properly escaping information to make sure the data is safe and clean for rendering in the browser.

Data Retrieval

As I mentioned in previous articles, one of the primary differentiators between a normal website and a web application is data storage.

And since WordPress uses its own database to manage data storage as well as makes APIs available for us to use for our own projects, it's obviously a web application.

Furthermore, just I discussed in the last article, understanding how to save data using the proper APIs is really simple, and once you've learned how to use one, using the rest of them is nearly just as easy. On top of that, learning how to retrieve data is arguably even easier.

That said, there are a few nuances that we need to consider when moving forward on retrieving data. But first, we'll review the database, take a look at how to retrieve information, and then we'll look at how to properly escape information before returning it to the browser.

Understanding the Database

In the previous article, we have a detailed overview of the tables to which you can write. You can read about this more in detail in the first article, but here's a summary of the tables that we discussed:

  • wp_options
  • wp_posts
  • wp_postmeta
  • wp_comments
  • wp_commentmeta

Remember, you can review all of this and more in the database description page in the WordPress Codex.

Reading From the Database

So with that as our refresher, it's time to actually look at how to retrieve information from the database.

Luckily, it's just about as easy as writing information to the database. The two main differences are:

  • We are using slightly different functions.
  • There's a little bit of work we need to do in order to make sure that the data we're displaying is cleanly formatted for the browser.

Before we look at how to manage the data, let's first look at how to read options from the database.

The Options Table

Recall from the last article that the way in which we go about writing data to the options table is by using the add_option or the get_option functions.

Remember: each takes in a unique key that is used to identify the value in the database, and the value associated with that key. In our previous example, I demonstrated the following:

if ( isset( $_POST['value'] ) && ! empty( $_POST['value'] ) {

    $clean_value = strip_tags( stripslashes( $_POST['value'] ) );
    add_option( 'my-value', $clean_value );

This means that we've sanitized and saved information to the database using the my-value key.

To retrieve this information from the database, we make the following call:

$my_value = get_option( 'my-value' );

It's almost too simple.

But there is a catch to the get_option function: We can actually specify a default value to return if one does not already exists.

For example, let's say we're going to look up a value for the key your-value, which does not exist.

// $your_value will actually equal FALSE
$your_value = get_option( 'your-value' );

In this case, the function will return FALSE; however, if we specify a second parameter, then we can return a default value:

// $your_value will actually equal an empty string
$your_value = get_option( 'your-value', '' );

Even still, nothing terribly complicated, right?

What About Theme Mod?

Before we look at how to retrieve information from the meta tables, it's worth mentioning that just like we set information using set_theme_mod, we can also retrieve theme settings using get_theme_mod.

Straight from the WordPress Codex:

Retrieves a modification setting for the current theme. Along with set_theme_mod() this function can sometimes offer theme developers a simpler alternative to the Settings API when there is a need to handle basic theme-specific settings.

Again, this is obviously meant for working with themes; however, I wanted to mention it here for the sake of being complete, and for the sake of rounding out the discussion started in the previous article.

Other than that, this is purely meant to showcase how options may be stored based on how you may be working with theme development; however, it's really outside the scope of the series on application development.

The Post Meta and the Comment Meta Tables

Now, back to talking about the database tables that are more applicable to application development and even content management.

In the last article, I demonstrated the API functions responsible for writing information to the meta data tables. Specifically, I outlined the following functions:

  • add_post_meta
  • update_post_meta
  • add_comment_meta
  • update_comment_meta

In similar fashion with the rest of the Options API, retrieving information from each of these tables is really easy, except it comes with a single 'gotcha'—by default, all information that's returned from these functions is done so in the form of an array.

This means that if you're to call:

$my_data = get_post_meta( get_the_ID(), 'my-post-information' );

Then the data will be returned to you in an array; however, if you're to pass TRUE to the function when calling it, then the data will be returned to you in a string:

$my_data = get_post_meta( get_the_ID(), 'my-post-information', TRUE );

Of course, there's no right way to do this. Instead, it depends on the information you want returned and/or how you want it returned. Because there's no one single way to do this, you have to judge your usage based on your application's implementation.

Escaping Data

Now, just as we needed to sanitize information prior to actually writing it to the database, it's also important that we properly escape the data after retrieving it from the database, but before rendering it to the browser.

Escaping data is the process by which we make sure the data that we're going to render to the user is secure. It's basically the sanitization done to data; however, it's done after the data has been retrieved from the database rather than done prior to writing it to the database.

When it comes to accepting data, there are four main functions of which we should be aware:

  1. esc_html is used to escape HTML blocks.
  2. esc_url is when you need to clean URLs that will be written out to text elements, attribute nodes, or anywhere else in the markup.
  3. esc_js is used to escape text strings that are used to echo JavaScript—primarily, inline JavaScript.
  4. esc_attr encodes several characters that can mangle the output if not handled properly.

The nice thing about this is that they generally work the exact same way, and the way to determine which one you need to use is relatively easy:

  • If you're rendering inline JavaScript, then use esc_js,
  • If you're rendering an attribute for an element, then use esc_attr.

Easy enough, right?

So, for example, let's say that you wanted to escape an attribute of an input field that's coming from the $_POST collection. To do this, you'd write the following code:

<?php echo '<input type="text" name="fname" value="' . esc_attr( $_POST['fname'] ) . '">';  ?>

It's little things like this that can go a long way towards making sure your application is robust in both data serialization and data retrieval.

And Now, on to Rewriting URL

We've covered a lot of ground in this series, but there's more to go.

Case in point: One of the nicest features of some of the more popular web application frameworks is how they handle URLs. In short, they provide clean URL schemes that make it really easy to understand the various actions that are available for the data models used throughout the application.

Out-of-the-box, WordPress doesn't offer the cleanest or clearest URLs; however, this can be modified through the use of the Rewrite API. In the next article, we're going to take a look at exactly how we can introduce custom rules for clean URLs that resemble something you'd see in a web application rather than in a content management system or a blog.

Related Posts
  • Code
    Creative Coding
    Using WordPress for Web Application Development: A ReviewApplication foundation 400
    Over the past few months, we've been taking a look at all of the features and aspects that make WordPress a potential foundation for application development. In fact, we've spent roughly 15 articles talking about all that WordPress offers. And though we'll be reviewing each of the points in this email, perhaps the biggest thing to take away that building web applications using WordPress is different than using many of the popular frameworks that are currently available namely because WordPress isn't a framework.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Custom Database QueriesApplication foundation 400
    Throughout this series, we've been looking at the various facilities that make it possible to treat WordPress as a foundation for web application development. Thus far, we've covered a lot of ground: We've talked about how WordPress is more of a foundation rather than a framework. We've discussed the nature of the the Event-Driven Design Pattern. There's been a discussion of Email, User Management, Saving Data, Retrieving Data ...and more. In the most recent articles, we've been talking a look at how to handle queries against the WordPress database through the use of WP_Query and WP_User_Query.Read More…
  • Code
    Mastering WordPress Meta Data: Understanding and Using ArraysMetadata
    In the first part of this series, we covered what WordPress meta data is, how it can be retrieved, and the various data types (such as objects or arrays) in which it can be returned. Now it's time to learn about the different types of arrays. When you write an array manually you know what its structure is an what the name of each index is. But when you are building arrays by querying a database, you are going to need to do some detective work to determine the structure of the data returned and the names of the indexes.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: WP_User_QueryApplication foundation 400
    In this series, we've been taking a look at how WordPress can be used to development web applications much like a number of different frameworks and other tools that are available. Starting in the last article, we began looking at the different options that we have as it relates to querying the WordPress data. First, we reviewed WP_Query.Read More…
  • Code
    Creative Coding
    Using WordPress For Web Application Development: Available Features, Part 7: CachingApplication foundation 400
    When it comes to building web applications, one of the most important things that we have to constantly be mindful of is performance. As they say, performance is a feature. And regardless of if you're a designer, developer, or a user, you know this intuitively to be true: When it comes to applications, we hate waiting. We get frustrated when things don't perform fast enough, or we have to wait longer than we believe that we should.Read More…
  • Code
    Creative Coding
    Using WordPress for Web Application Development: Features: Saving DataApplication foundation 400
    When it comes to the web, almost any application that runs within your browser is backed by a data store of some type. Usually, these data stores are in the form of a type of database. Until recently, most applications were built on top of some type of SQL database, but with the rise of document-based databases such as CouchDB, other applications have begun to use other backends as well.Read More…