Skip to content

Instantly share code, notes, and snippets.

@victorjonsson
Created December 16, 2012 09:12
Show Gist options
  • Save victorjonsson/4305790 to your computer and use it in GitHub Desktop.
Save victorjonsson/4305790 to your computer and use it in GitHub Desktop.
<?php
/**
* Class that manages all post meta attached to posts by my plugin. This class can be used as an
* ordinary PHP object (stdClass)
*
* @requires PHP version >= 5.1, WordPress version >= 1.6
* @package MyPlugin
* @since 0.1
*/
class MyPlugin_Post_Meta implements IteratorAggregate {
public static function get($name, $default=false, $ns = null)
{
$obj = new self($ns);
$val = $obj->$name;
if($val === false && $default !== false)
$val = $default;
return $val;
}
public static function set($name, $val, $ns=null)
{
$obj = new self($ns);
$obj->$name = $val;
}
private $ns;
private $post_id;
public function __construct($post_id=null, $ns = null)
{
if($post_id === null) {
global $post;
$this->post_id = $post->ID;
} else {
$this->post_id = $post_id;
}
if( $ns === null )
$ns = plugin_basename(__FILE__);
$this->ns = '_'.$ns.'_';
}
public function __get($name)
{
return get_post_meta($this->post_id, $this->ns . $name, true);
}
public function __set($name, $val)
{
if($val === null) {
$this->delete($name);
} else {
update_post_meta($this->post_id, $this->ns . $name, $val);
}
}
public function __isset($name)
{
return $this->exists($name);
}
public function __unset($name)
{
$this->delete($name);
}
public function exists($name) {
return $this->$name ? true:false;
}
public function deleteAll() {
global $wpdb;
$wpdb->query("
DELETE `meta_key`, `meta_value`
FROM $wpdb->postmeta
WHERE
`post_id` = $post_id
AND `meta_key` LIKE '".$this->ns."%'
");
clean_post_cache( $this->post_id );
}
public function delete($name) {
delete_post_meta($this->post_id, $this->ns . $name);
}
public function getIterator()
{
global $wpdb;
$data = array();
$wpdb->query("
SELECT `meta_key`, `meta_value`
FROM $wpdb->postmeta
WHERE `post_id` = $post_id
");
$ns_length = strlen($this->ns);
foreach($wpdb->last_result as $k => $v) {
if( substr($k->meta_key, 0, $ns_length) == $this->ns )
$data[$v->meta_key] = $v->meta_value;
}
return new ArrayIterator($data);
}
}
// Use this class as an ordinary php object (stdClass)
$meta = new MyPlugin_Post_Meta();
$meta->some_option = 'My value'; // the value can be of any type
if( isset($meta->other_option) ) {
unset( $meta->other_option );
}
if( $meta->perhaps_a_meta ) { // trying to access undefined meta will return false (no error triggered)
//...
}
foreach( $meta as $meta_name => $val) { // tou can traverse the option object as if it were an array
// ...
}
// Static short hand functions (post needs to be in global)
MyPlugin_Post_Meta::get('some_option', 'default value');
MyPlugin_Post_Meta::set('some_option', null); // setting the meta to null will remove it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment