Created
July 4, 2014 13:53
-
-
Save adrian7/12ff8e3b6c2bc254401c to your computer and use it in GitHub Desktop.
WordPress - class to extract your post meta in the form of an object; more elegant, easier to cache
This file contains hidden or 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
/** | |
* wp_view_options - extracts post meta as object members | |
* @author Adrian S. (http://www.gridwave.co.uk/) | |
* @version 1.0 | |
* | |
* Basic usage example: | |
* | |
* $view_options = new wp_view_options( get_the_ID() ); | |
* ... | |
* if( $view_options->background_color ) | |
* echo ('#' . $view_options->background_color ); | |
* | |
* Advanced usage example: | |
* | |
* $convert = array('yes'=>true, 'no'=>false); | |
* $view_options = new wp_view_options( get_the_ID(), $convert); | |
* ... | |
* if( $view_options->is_featured ) //in DB, is_featured may be yes or no, however because we have convert on, the value will be converted accordingly; | |
* echo 'post-featured'; | |
*/ | |
class wp_view_options{ | |
private $store = array(); | |
private $multi = array(); | |
private $conversions = array(); | |
private $post_id = 0; | |
public function __construct($post_id=0, $multi=array(), $conversions=array()){ | |
global $post; if( empty($post_id) ) $post_id = $post->ID; $this->post_id = $post_id; $this->multi = $multi; $this->conversions = array_change_key_case($conversions, CASE_LOWER); | |
} | |
public function convert($value){ | |
$unit = strtolower($value); return strlen($value) ? ( isset($this->conversions[$unit]) ? $this->conversions[$unit] : $value ) : null; | |
} | |
public function __get($name){ | |
if( $name == 'post_id' ) | |
return $this->post_id; | |
if( isset($this->store[$name]) ) return $this->store[$name]; | |
$value = get_post_meta($this->post_id, $name, in_array($name, $this->multi, true) ? false : true); | |
$value = $this->convert($value); | |
$this->{$name} = $value; | |
return $value; | |
} | |
public function __set($name, $value){ | |
if( $name == 'post_id' ) | |
_doing_it_wrong(__CLASS__ . '->__set()', 'Post ID cannot be reset this way. Please create another instance of the class', '1.0'); | |
$this->store[$name] = $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment