Software, Development, and WordPress

Refactoring Input Sanitization with The WordPress Settings API

This post is part of a series on Sanitization with the WordPress Settings API. Here is Part 3.

In continuing to work on sanitizing arrays of input with the WordPress Settings API, there are two things that we need to do:

  1. Refactor the existing code that we have so it’s as clean as possible
  2. Determine what fields we’re going to use to mark as required

In this particular article, we’re going to focus on both. This particular article is going to include the code necessary to tighten up our existing code and then we’ll begin laying the ground work for introducing a new class – a validation class – when we begin looking at the second step.

Inputs From The WordPress Settings API

Ultimately, we’re working our way to setting up what fields are required and what their corresponding error messages should be – but we’ll get to that starting in the next article.

For now, let’s focus on tightening up the code that we currently have (with the help of some of the comments over the past few posts) and then determine what fields we want to mark as required.

Refactoring Existing Code

In the last article featuring code, we left our sanitize function looking like this:

And that works, but as one commenter pointed out, it’s a bit redundant:

To be honest, I’m not super sure what you’re trying to do here but in any case, the isset check is redundant. You’re iterating over the keys of the $input array, so the current index is always set.

The thing is, whenever you submit a collection of input fields via the $_POST array in PHP, they are going to have a value even if the value is an empty string. Looking to see if an empty string exists is part of what we’ll be doing in the next step of this article.

For now, let’s clean up some of the code that we currently have. Namely, let’s remove some of the redundancy that we have in checking to see if a value is set or not.

At this point, we’ve got the code as lean and as functional as it can be given it’s current state. Of course, we’ll be adding more to this over the next few articles, but first we need to identify what we want the user to be required to enter.

Setting Required Fields

Given the work that we’ve done this far, WordPress should be saving data to the database. Eventually, we’re going to look at retrieving the information from the database, but only after we’ve marked certain fields as required.

So let’s do that now. Given the following screen shot that we’ve been using:

An Example Settings Page

An Example Settings Page

What fields should be required? For the purposes of this series of articles, I’m going to chose:

  • Address 1
  • City
  • Postal Code

But you can feel free to choose whatever you want as the strategies that we’ll be employing through the use of the validation class that we’re going to introduce is going to make it easy to handle each field on its own.

And that’s where we’re headed next.

Series Posts

  1. Sanitizing Multiple Values with the WordPress Settings API
  2. Sanitizing Arrays: The WordPress Settings API
  3. On Pause: The WordPress Settings API
  4. Refactoring Input Sanitization with The WordPress Settings API
  5. Validating Input via the WordPress Settings API
  6. Validation and Sanitization in the WordPress Settings API


  1. Jason Lemieux

    Congrats on the awesome series, Tom. This will be a huge resource for people. What a guy.

    • Tom

      Thanks Jason – still have a lot to cover and it’ll be intermingled with some other content, but hopefully by the end of the series, it’ll provide some guidance on how to easily move forward with this :).

  2. Rick

    Hey Tom,

    While puttering about getting familiar with some things I ran across this

    I cannot attest to its accuracy, did not look at its code.

    But, what I was doin’ (not sure its sanguine to really do in production? Opinion welcome) was looking at PHP trash pickup, garbage collection.

    I understand the theories of GC and TP! LOL… Read some of how PHP deals with it. Global stuff is really killer to TP as it doesnt get rid of crap… Hmmm… Ohh booo… That is to say essentially PHP works like several interpreted managed engines. As parsing in code it keeps count of references. Only when something is essentially completely deferenced will it put it up for GC. Garbage Collection can be forced via gc_collect_cycles();

    Sure as beans doesnt tend to clean up global data. I didnt try anything really simple simple since WP is the candidate here. Download the GIT zip, and slap this in the root index.php of WP:

    if( isset($_GET[‘php-benchmark-test’]) ) {

    require DIR.’/lib/PHPBenchmark/Monitor.php’;

    \PHPBenchmark\Monitor::instance()->init( !empty($_GET[‘display-data’]) );


    extract the “lib” directory in the zip into the WP install root.

    Do a HTTP to the WP install and just add ?php-benchmark-test unto the URL

    It’ll spit ram use and time to run.

    Very different result from memory_get_usage();

    In any event, I have a bunch of arrays for example for theme support. So add_theme_support, register_menu’s, Register_sidebars (widgies) all sit within a array. The plan was consume them via a variable function aka:

    $theme_support = array (

    ‘add_theme_support’=>array(‘post-formats’ => array(‘aside’, ‘gallery’, ‘image’),

    ‘html5’ => array(‘comment-list’, ‘comment-form’, ‘search-form’, ‘gallery’, ‘caption’)

    …. blah blah blah),

    ‘register_nav_menus’=>array(blah blah bla) etc etc

    Sit in a foreach and just iterate through it all and use the array key in a variable function (aka: $func_key($support_data);

    WP doesnt like it at all.

    So… anyways… back to garbage collection.

    Tried dumpin the arrays after they are initialized. Obviously the widgets one being “actioned” on widgit-init little picky as to placement in the code.

    As globals, refused to drop em.

    So… I put them in a static class aka: “theStaticClass::” and lo and behold garbage collection would clean em up freeing up ram.

    So I decided to play around as to where. Believe it or not, this can be done before the loop. Can massacre the widget attributes array, the post formats array, the menu array, havent tried post thumbnails yet, that ones prolly sketchy assuming front end admin or user U/L’s. Maybe not.

    This is a full theme with 15 front posts showing and 4 comments on each, Three customs post types and 6 taxonomies (shared between all three post types) run out on a dual core E7300 running Xampp.

    First number is ram usage via memory_get_usage starting at WP index.php root and collected last thing in footer.php, last one is phpbenchmark.

    This is with doing garbage collection:

    — Usage Bytes: 9699328

    [phpbenchmark time=0.395500 memory=9.397600 files=88 classes=213]

    Not doing the garbage collection:

    — Usage Bytes: 9699328

    [phpbenchmark time=0.187500 memory=9.404100 files=88 classes=213]

    As we can see, memory_get_usage, no change. phpbenchmark shows a little memory savings as the arrays are dumped. Garbage collection consumes time clearly.

    And again, this is a full theme, though the “theme engine” has a good bit more code to write (remember, all OOP theme engine thats easy peasy enough so my gal can make themes is the “gig”).

    Flip the theme to twenty thirteen theme, no garbage collection:

    [phpbenchmark time=0.495100 memory=9.389000 files=88 classes=206]

    Twenty Fourteen:

    [phpbenchmark time=0.555600 memory=9.516400 files=93 classes=208]

    This is all quite encouraging, The OOP theme framework without GC enabled is absolutely blowing the doors off the themes come with WP and has about the same footprint with most of it not yet optimized.

    This is rather surprising to me.

    Its drastic. We are talking 4 and 5:1. I need set this into a linux server here and see how that shapes up.

    One would think this should be going the other way?!?!?!

    The procedural theme being faster than the OOP but clearly, does not seem be the case at all.

    Need take a look at a WP “just nothing” install, see what it consumes to try get an semi-brain load of true consumption of time and such. The benchmark docs also show NodeJS pounding on the sever which I will try when I get to that.

    The BIG question I have is, should this provide option for garbage collections or not? Clearly, as with any GC there is the time to collect .vs. ram restored and when issues. If a script is at its end doesnt make much sense to free ram. If not, can make sense as resources allow for more page sessions.

    But, my concern is WP itself. That being, older or newer versions of WP do things a bit different and all of a sudden where garbage collection is to take place results in a site not having its assets and looking like a train wreck?

    • Tom

       The BIG question I have is, should this provide option for garbage collections or not? Clearly, as with any GC there is the time to collect .vs. ram restored and when issues. If a script is at its end doesnt make much sense to free ram. If not, can make sense as resources allow for more page sessions.

      When it comes to garbage collection and script performance, I’m not nearly as into it as I used to be (call me lazy, but it often comes down to an issue of timing – ironically, I guess – for me). I think that when it comes to PHP, performance is going to vary by version as with most interpreted languages, though I don’t know how things stack up from version to version.

       But, my concern is WP itself. That being, older or newer versions of WP do things a bit different and all of a sudden where garbage collection is to take place results in a site not having its assets and looking like a train wreck?

      No clue how this pans out. I’d imagine the most recent versions of WordPress coupled with more recent versions of PHP are your best bet. Again, though, it’d be more fun to profile to see how it turns out and then offer guidance from there.

  3. Rick

    I havent run like a real profiler over anything yet. Sorta still getting my bearings on WP. I am PHP aware but not ultra-aware. I guess “static anything” is faster than not. Even regular function calls are slower from what I’d read last night. Was looking at variable functions like I said, bit slower than a normal function call but very very little. But static seems to be significantly more rapid. Was also surprised that static data such as say a var or array in a class can be changed. That brings in some interesting prospects. Though coming from .NET so much of this feels like I am violating some poor chimp.


    I mean here’s kinda the deal. She knows zero about coding. CSS, she can do the basic styling stuff’s.

    Bootstrap, Foundation & Gumby she sorta gets.

    So I am building this based on keeping in mind that she, the theme builder has pretty much zero to go on other than layout and base stuff. “Want this feature and that etc”.

    I dont think I’d publically release the page builder stuff. Thats actually not in PHP at all. That is to say, the presently “bootstrap” layout builder and theme feature setup (aka: aside’s, this/that, all the theme support jibe). Thats all done in a Windows App. So it essentially is a braindead little layout application where WP options can be set. It then outputs the actual production file’s to be consumed by the theme engine.

    Doing all that in PHP in the backend with JS etc. just made zero sense to me. Alot more work and alot less function capable and no ability to really rapidly prototype for her, and of course I dont need worry about “Rick… I think I broke something” LOL.

  4. Zadli

    Helped!! Thanks for the code :D

Leave a Reply

© 2020 Tom McFarlin

Theme by Anders NorenUp ↑