Last active
June 30, 2022 12:33
-
-
Save ericjuden/9256827 to your computer and use it in GitHub Desktop.
WordPress Options Class with Support for storing and retrieving JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class My_Plugin_Options { | |
var $options; | |
var $option_name; | |
var $is_site_option; // Are we using Multisite and saving to global options? | |
function My_Plugin_Options($option_name, $is_site_options = false){ | |
$this->option_name = $option_name; | |
$this->is_site_option = $is_site_options; | |
if($this->is_site_option){ | |
$this->options = get_site_option($this->option_name); | |
} else { | |
$this->options = get_option($this->option_name); | |
} | |
// Check if options are JSON | |
if(!is_array($this->options)){ | |
$temp_options = json_decode($this->options); | |
if(json_last_error() == JSON_ERROR_NONE && !empty($temp_options)){ | |
$this->options = $temp_options; | |
} | |
if(empty($this->options)){ | |
$this->options = array(); | |
} | |
} | |
} | |
function __get($key){ | |
if(is_array($this->options)){ | |
if(isset($this->options[$key])){ | |
return $this->options[$key]; | |
} | |
} elseif(is_object($this->options)){ | |
if(isset($this->options->{$key})){ | |
return $this->options->{$key}; | |
} | |
} | |
return false; | |
} | |
function __set($key, $value){ | |
if(is_array($this->options)){ | |
$this->options[$key] = $value; | |
} elseif(is_object($this->options)){ | |
$this->options->{$key} = $value; | |
} else { | |
// Do nothing | |
} | |
} | |
function __isset($key){ | |
if(is_array($this->options)){ | |
return array_key_exists($key, $this->options); | |
} elseif(is_object($this->options)){ | |
return property_exists($this->options, $key); | |
} else { | |
return false; | |
} | |
} | |
function save(){ | |
if($this->is_site_option){ | |
update_site_option($this->option_name, json_encode($this->options)); | |
} else { | |
update_option($this->option_name, json_encode($this->options)); | |
} | |
} | |
} | |
?> |
To pull the value back, you'd simply call:
$this->options->my_setting1
Thank you! Now I can make new options/value and change value of those options.
I want to understand how can I do something more:
- Delete a key (like 'my_setting1')
- Check if a key exist or not
- Can we make a nested jSON with this?
Many thanks! :D
My another question :D! I can set nested jSON like this:
- $this->options->my_setting3 = array('a3'=>'A3','b3'=>'B3');
My question is how I can modify value 'A3' of 'a3' key only...
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To pull the value back, you'd simply call:
$this->options->my_setting1