3
votes

And there I thought I knew Wordpress well. It now seems that update_option() auto-escapes code. If I want to save some Javascript or HTML code in an option, this behavior renders the code unusable.

I refuse to do a str_replace on the returned value to filter out every backslash. There has to be a better way.

Here's the PHP for the text box to enter some code:

$option = unserialize(get_option('option'));

<textarea name="option[box]"><?php echo $option['box']; ?></textarea>

This is what happens after submitting the form (in essence):

update_option('option', serialize($_POST));

Any ideas?

Edit: I now got it to work by using PHP's stripslashes() where the script has to be rendered, and htmlentities(stripslashes()) in the text box to display the stored code. While this does the job, I'd still like to know if there is a better solution.

2
Instead of using that built in function why not use the wpdb class to do all your database work? - hsatterwhite
Would be easier/better than using update_option and get_option? If you have a link to an example of what you mean, that would be greatly appreciated! Thanks. - bobsoap
This will require you to understand the WordPress database schema a little bit, but it's straight forward: codex.wordpress.org/Function_Reference/wpdb_Class - hsatterwhite
Thanks for the link hsatterwhite, I do have an understanding of WP's db schema but for this purpose, it seems like too big a workaround - at least to me. I'm not sure what the best practice is here. I've updated my post above with what I got it to work for now. Thanks a lot for your input! - bobsoap
Any time :) My thought here was skipping WP's prebuilt function and using the wpdb class to update and retrieve that option column as needed. So you could literally put what ever you want in there. - hsatterwhite

2 Answers

2
votes

It now seems that update_option() auto-escapes code.

It only sanitizes the value for database entry. You'll find the real troublemaker is around line 750 in wp-settings.php, and the WP function add_magic_quotes().

Yep, you read that right, add magic quotes!

For some reason, WordPress decided to enforce magic quotes, so you'll always need to stripslashes on GET and POST when writing plugins and the like.

2
votes

That's true @TheDeadMedic stripslashes must be used like;

echo stripslashes(get_option( 'option' ));