WordPress.org

Ready to get started?Download WordPress

Forums

How to save plugin options as an array in 2.5? (8 posts)

  1. Glenn Ansley
    Member
    Posted 6 years ago #

    Hi,
    I've been storing my admin options in a single option as an array from some time now based on this tutorial.

    What process would I have to take to continue saving my options in an array based on the new option handling process mentioned here?

    In short, the above codex page's example would save every field in my form as a separate option. How would I place each field into an array and save the array as a single option?

    Thanks.

  2. nickohrn
    Member
    Posted 6 years ago #

    You don't need to use the "easy" option saving that is available. That is just an option for you if you want to do it that way. If you want to continue saving as an array, all you have to do is create an array containing all your option values and then call update_option('my_option', serialize($option_array));

  3. Glenn Ansley
    Member
    Posted 5 years ago #

    Thanks. I've never used serialize() before. I've just referenced my array. Guess I need to look into that.

  4. nickohrn
    Member
    Posted 5 years ago #

    Just make sure you unserialize when it comes out of the option field, too, otherwise you'll just have a big string of gobbledy good instead of an array.

  5. Glenn Ansley
    Member
    Posted 5 years ago #

    What's the benefit of serialization?

  6. yearginsm
    Member
    Posted 5 years ago #

    It allows an array to be stored as a string, particularly handy if you need to store data in a manner that does not require a set schema. Let's say I had four options for a plugin:

    Array
    (
        [list_begin] => <ul>
        [list_end] => </ul>
        [list_item_begin] => <li>
        [list_item_end] => </li>
    )

    If I really did not want to create four separate options in the wp_options table, I could serialize that array (it works for objects too) and write that as one long string to be stored as one option.

    a:4:{s:10:"list_begin";s:4:"<ul>";s:8:"list_end";s:5:"</ul>";s:15:"list_item_begin";s:4:"<li>";s:13:"list_item_end";s:5:"</li>";}

    Once that is in the table, you can use the unserialize() function to return it to an array for use in your plugin. If you look at the /wp-admin/options.php page, you will see a good bit of the WordPress internals and some other plugins handle data in this way.

  7. nickohrn
    Member
    Posted 5 years ago #

    Great explanation there, yearginsm, and pretty much the exact same I was going to give.

  8. Glenn Ansley
    Member
    Posted 5 years ago #

    Thanks for the explanation. I think WordPress must automatically do this because I never use the serialize and unserialize functions but my DB holds the info as described above and and I can foreach thorough it when i pull it back out via get_option().

Topic Closed

This topic has been closed to new replies.

About this Topic