Skip to content

Instantly share code, notes, and snippets.

@vanaf1979
Last active October 8, 2019 08:30
Show Gist options
  • Save vanaf1979/0382ec0b15cbb16d9f13d65905652795 to your computer and use it in GitHub Desktop.
Save vanaf1979/0382ec0b15cbb16d9f13d65905652795 to your computer and use it in GitHub Desktop.
Gist for my article WordPress: Access post meta fields through WP_Post. https://vanaf1979.nl/wordpress-access-post-meta-fields-through-wp-post/
<?php
// From wp-includes/class-wp-post.php
/**
* Getter.
*
* @since 3.5.0
*
* @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