-
Notifications
You must be signed in to change notification settings - Fork 0
Using sanitation filters and methods
All the sanitation filters are defined as methods inside sanitation-methods.php. The following sanitation filters are available out of the box:
- plain_text
- id
- class
- color_picker
Please note that by default the colorpicker and email field types are sanitized using their respective filter (color_picker and email). Editing the methods for these filter will also alter the way the colorpicker and email fields are filtered.
To use a filter add the sanitize
key to your field array. The value of the key should be an array containing all the names of the sanitation methods to be used (without the sanitize_ prefix). For example, to use the sanitize_id method on an input field one may create the following field:
array(
'title' => 'This will be sanitized:',
'id' => 'example_text',
'type' => 'text',
'sanitize' => array('id'),
),
With the simple Meta Boxes class creating a filter is as easy as creating a new method in sanitation-methods.php. There are three important rules to consider when creating a new sanitation method:
- The name of the method must begin with sanitize_ because the Simple Meta Boxes class uses this prefix to index its sanitation methods when it is instantiated.
- The method must accept a parameter that will accept the data to be sanitized (usually referred to as $data). The Simple Meta Boxes class will automatically pass the required data to this parameter.
- The method must return the sanitized data, or else the data will be lost.
Lets create a new sanitation method together. The sanitation method will remove anything but digits, making sure the field will contain only numbers. First Add the following method to sanitation-methods.php
public function sanitize_number($data)
{
$data = preg_replace('/\D/', '', $data);
return $data;
}
We called the method sanitize_number
, so the filter for it will be called number
. The method accepts the $data parameter, which contains the data input from the user. It then runs it against a regex expression to replace any non-numeric characters. Finally it returns the new data back to the class for saving.
Now this method is ready and can be used as a filter in an actual field. Let's create an example field that will utilize the filter. First, create a metabox (see adding meta boxes to learn how). Next lets add a new age field. The age field should accept only digits and as such will make use of the filter we created.
array(
'title' => 'Age',
'id' => 'age_example',
'type' => 'text',
'sanitize' => array('number'),
),