Create a gist now

Instantly share code, notes, and snippets.

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));
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment