WordPress PHP – How to update plugin setting value in main file

This is from inside my WordPress plugin, inside the main file:

function my_plugin_install() {

    $my_site_url = get_site_url();

    $my_options['my_site_url'] = $my_site_url;

    // Save

}

register_activation_hook(__FILE__, 'my_plugin_install');

Currently, the install is successful but the ‘my_site_url’ option is not saved. I’m assuming because the way I’m using the $my_options array at this point doesn’t mean anything. It should save this data to the wp_options table.

Read More

I can’t seem to get this to save, or even find a way to test this as using “echo” gives WordPress an error during install. Is there a best method for running a script and updating the database during install?

Thanks in advance.

Related posts

1 comment

  1. You need to use the WordPress function update_option to save your option value:

    function my_plugin_install() {
        $my_site_url = get_site_url();
        update_option('my_site_url', $my_site_url);
    }
    
    register_activation_hook(__FILE__, 'my_plugin_install');
    

    And then later, when you need that value, you can use get_option:

    $my_site_url = get_option('my_site_url');
    

    *UPDATE
    Since it appears you want to manage multiple of your own options, then I suggest using a simple “utility” function, like so:

    function update_my_option($key, $value) {  
        // Load all of the option values from wp_options
        $all_options = get_option('my_options');
        // Update just the one option you passed in
        $all_options[$key] = $value;
        // Save to wp_options
        update_option('my_options');
    }
    

    And, an appropriate getter function:

    function get_my_option($key, $default = NULL) {
        // Load all of your options from wp_options
        $all_options = get_option('my_options');
        // Return just the one option you are asking for
        return (isset($all_options[$key])) ? $all_options[$key] : $default;
    }
    

    Then, rather than calling update_option directly, you’ll call this function, as illustrated below:

    function my_plugin_install() {
        $my_site_url = get_site_url();
        update_my_option('my_site_url', $my_site_url);
    }
    

    And, to get one of your options:

    $my_site_url = get_my_option('my_site_url');
    

Comments are closed.