Save a plugin setting with a sanitize callback

Description: Register an option site_slogan in a plugin, which cleans the value with sanitize_text_field. Save the value <b>Learn</b> fast and print what is stored.

Hint:

  • register_setting() with sanitize_callback runs a filter every time update_option() saves the option.

Solution

register_setting( 'my_group', 'site_slogan', array(
	'type'              => 'string',
	'sanitize_callback' => 'sanitize_text_field',
) );

update_option( 'site_slogan', '<b>Learn</b> fast' );
var_dump( get_option( 'site_slogan' ) );
Output

string(10) "Learn fast"

How it works

  • register_setting() connects the sanitize function to the option name.
  • The tags are removed before the value goes to the database, so the stored value is plain text.
  • In a real plugin you call register_setting() on the admin_init hook.

Read Plugin Settings Page.


Learn more about the similar topics:
Tutorials
WordPress Security
WordPress Data Validation, Sanitizing and Escaping
Exercises & Assignments
Save a plugin setting with a sanitize callback
Interview Questions & Answers
What is the recommended permission for WordPress files and folders?
What is the difference between sanitizing, validating and escaping in WordPress?
What is a nonce in WordPress?
How to prevent SQL injection in WordPress?
How to secure a WordPress website?