Saving javascript with the update_option() function


I am writing a plugin which adds a simple option page. On the options page there is a textfield where the user can add a specific script when then will be available in the footer on the front-end using the wp_footer() function.

Now, when the user submits the script to the wp_options table, I assume that the script will need to be sanitized so a possible hacker can't use the textarea field to hack / destroy the database. Is that correct?

If so, how should I go about sanitizing the script?

I would love a practical example.


  • Predrag Dubajic

    Hey Mika,

    Hope you're doing well today :slight_smile:

    update_option() is a WordPress function and WordPress should sanitize those for you as far as I know.

    Let me flag some of our second level support dev guys in here and maybe they can give us some more info regarding this.
    Please note that, developer response might be slower than usual staff response, so we appreciate your patience on this.

    Best regards,

  • Vinod Dalvi

    Hi Mika,

    In the update_option function the sanitize_option function i called that sanitizes various option values based on the nature of the option so anything that uses the built-in update_option() and get_option() functions will serialise and un-serialise arrays and objects as required, as well as sanitising the values.

    But on the following code page it has written that " The $option (option name) value is escaped with $wpdb->prepare before the INSERT statement but not the option value, this value should always be properly sanitized."

    So for precautions we should sanitize the value before saving it using the function update_option.

    I have tested it on my test site JSON encoding script and saving it in the WP options and retrieving it by decoding it as shown in the following code.

    $test_update_option = '<script type="text/javascript">
    			var str = $(" #wrapper .entry-title").html();
    			if( typeof str !== "undefined" && str.trim() == "services headline" ){
    				$(" #wrapper .entry-title").html("Marketplace Products");
    update_option( 'test_update_option', json_encode( $test_update_option ) );
    function add_custom_scripts(){
    	echo json_decode(get_option( 'test_update_option'));
     add_action('wp_footer', 'add_custom_scripts');

    It worked fine for me as shown in the attached screenshot and i hope it will also help you.

    Please advise if you have more questions.

    Best Regards,
    Vinod Dalvi

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.