Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shelob9/7cd91c18409cf28085d8 to your computer and use it in GitHub Desktop.
Save Shelob9/7cd91c18409cf28085d8 to your computer and use it in GitHub Desktop.
<?php
//Add meta fields
update_post_meta( 1, 'hats', 'bats' );
update_post_meta( 1, 'bread', array( 'rye', 'sourdough' ) );
//get the WP_Post object
$post = get_post( 1 );
//use it's __get to get its meta fields.
echo $post->hats; // "bats"
print_r( $post->bread ); //the array
var_dump( $post->not_a_real_key ); //empty string
<?php
//how it works in core
//Copied from post.php ~L718 in WordPress 4.3 (much GPL)
/**
* Getter.
*
* @param string $key Key to get.
* @return mixed
*/
public function __get( $key ) {
if ( 'page_template' == $key && $this->__isset( $key ) ) {
return get_post_meta( $this->ID, '_wp_page_template', true );
}
if ( 'post_category' == $key ) {
if ( is_object_in_taxonomy( $this->post_type, 'category' ) )
$terms = get_the_terms( $this, 'category' );
if ( empty( $terms ) )
return array();
return wp_list_pluck( $terms, 'term_id' );
}
if ( 'tags_input' == $key ) {
if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) )
$terms = get_the_terms( $this, 'post_tag' );
if ( empty( $terms ) )
return array();
return wp_list_pluck( $terms, 'name' );
}
// Rest of the values need filtering.
if ( 'ancestors' == $key )
$value = get_post_ancestors( $this );
else
$value = get_post_meta( $this->ID, $key, true );
if ( $this->filter )
$value = sanitize_post_field( $key, $value, $this->ID, $this->filter );
return $value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment