Three Ways You Can Use a Hash In Your WordPress Plugin

Posted on:

A useful tool to put in your programming toolkit is hashing. A hash is string that contains a bunch of seemingly random characters, however they are not random at all. A hash is created from input data, which is then garbled up in a very specific way, and then output as the seemingly random garbled up string. The cool thing about hashes, is that if they are built from the same input, you will always get the same hash.

So, in other words, if I created a hash from Hello world!, the hash would look something like 86fb269d190d2c85f6e0468ceca42a20.

There are many ways to generate a hash, and each one has their benefits and disadvantages. md5 is common because it generates the hash quickly, but the hash isn't technically secure, so you wouldn't want to use it to generate passwords, or for any security-related circumstances. A hash is a one way conversion. In-other words, they are not intended to be converted from the hash back to the original value.

Let's get into three different ways that I often use hashes in my own plugins. There's many more, but these are the most-common circumstances that come to mind.

Cache Keys

Sometimes, the best way to improve the performance of your plugin is to use the WordPress object cache. This allows you to bypass entire chunks of code in your system, and dramatically reduce the number of database query calls you make.

The WordPress object cache requires that you provide a unique cache key for your cached item. In most cases, this isn't difficult, but what happens if you're trying to cache results based on a large array of arguments? Each time the arguments are different, the cache key needs to also be different to reflect that. An effective way to handle this is to convert the array into a hash.

{
  "name": "acf/snippet",
  "attributes": {
    "id": "block_6105c8644a780",
    "name": "acf/snippet",
    "data": {
      "language": "php",
      "_language": "field_60d7f32b1b540",
      "code": "<?php\r\n\r\n/**\r\n *  First, normalize the array. The hash comes out different based on The\r\n *  order of the items in the array. Sorting ensures that the data is always\r\n *  provided in the same fashion.\r\n **/\r\n$normalized_args = asort( $args );\r\n\r\n/**\r\n * Next, convert the array into a serialized string.\r\n * Hashes are built from strings, not arrays, so we have to convert our array\r\n * into a string first\r\n **/\r\n$args_string = serialize( $normalized_args );\r\n\r\n/**\r\n * Finally, Use md5 to convert the args into a hash.\r\n * Add a prefix to the hash to further reduce the probability of collisions.\r\n **/\r\n$cache_key_hash = 'cache_specific_prefix_' . md5( $args_string );\r\n\r\nwp_cache_add( $cache_key_hash, 'Cached data would go here' );\r\n\r\n?>",
      "_code": "field_60d7f36c1b541"
    },
    "align": "",
    "mode": "edit"
  },
  "innerBlocks": []
}

Quickly Ensure Database Records are Unique

Sometimes when you're building a custom post type, or a custom database, you want the records to always be unique, and never save duplicates in the database. Perhaps you want to take this a step further, and automatically detect if the record already exists, and instead simply update it instead. Most of the time, this can be accomplished using the record's ID field, but what if you don't have the ID, but do have all of the data that was used to create that ID? You can still find the record, but you have to run a pretty large query to find the item, because you'll have to query against every column in the table.

Instead of querying against all of the database columns, what if you set up your database table to include a hash column, that stores the hash based on how the record is saved? Now you have a unique identifier for your database, and you can generate it at any time using the database columns themselves. With that, you only have to query against one column, and you could easily index the hash column to make it just about as fast to do this as looking it up by the ID itself.

To Generate Secret Links

I have built some plugins in the past that use a secure hash (read: not md5) to generate a public URL that can only be visited if you know the hash associated with the page. For example, you could create a quiz app that, when done, generates a unique URL for the quiz results, so that the person can share their results online with other people. These aren't intended to be indexed by Google or anything, it's just a results page.

This kind-of thing is also used by Google Docs when you make your document publicly share-able. A gigantic hash is appended to the end of the URL, making it as difficult to crack as possible.

Conclusion

When people think of hashes, they tend to think of them as strictly things to use for security purposes, but there are many cases where how the hash is built can be used to your advantage. With a little forethought, you can use a hash to create a unique key based on the data itself, instead of something manually added. Playing with this dynamic allows you to solve problems that are otherwise difficult to solve effectively.