When doing research for a new magazine theme I’m building I encountered an interested subject. I have a lot of “design options” that need to be saved into database. Since I don’t want to save them separately as options (I will have 20+ calls to database) I planned to serialize the options array and store a single value in database.
The solution was obvious:
update_option (design_options,serialize($design_array)) // where design _array is the array with design options
The above instruction should save in wp_options table a new record called design_options having as value the serialized version of the $design_array. Easy, right?
I encounter the first problems when I try to retrieve those values. The code below should take the value from database , unserialize it and make the saved array ready to use.
$options_content=unserialize(design_options);
Well, this didn’t work.
After a hour of debugging with no success I researched the issue over the internet and it seems that using the base64_encode and base64_decode solve the issue.
To store:
$options_to_insert=base64_encode(serialize($options));
update_option('design_options', $options_to_insert);
To retrieve:
$design_options=get_option('design_options');
$options=unserialize(base64_decode($design_options));
Although this is working piece of code is not the actually the right solution. After doing a little more research I discovered that update_option and get_option handle the serialization & desearialization of an array by default. Read this article.
So the actual solution is not to use serialize at all. Update_option will detect that the value you need to store is an array and will serialize it before insert. The get_ option will deserialize and the array will be ready to use in a single instruction.
This is the only thing you need to do:)
update_option('design_options', $array_for_store); //to store
$design_options=get_option('design_options'); //to retrieve
