Skip to content

Instantly share code, notes, and snippets.

@ericjuden
Last active June 30, 2022 12:33
Show Gist options
  • Save ericjuden/9256827 to your computer and use it in GitHub Desktop.
Save ericjuden/9256827 to your computer and use it in GitHub Desktop.
WordPress Options Class with Support for storing and retrieving JSON
<?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));
}
}
}
?>
@gianghl1983
Copy link

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