Skip to content

Instantly share code, notes, and snippets.

@joehoyle
Created July 26, 2011 17:15
Show Gist options
  • Save joehoyle/1107255 to your computer and use it in GitHub Desktop.
Save joehoyle/1107255 to your computer and use it in GitHub Desktop.
An Idea for a WordPress Post class
<?php
/**
* This is a take on making the Post object in WordPress a little more object-y. As well as wrapping
* some basic function like get_the_title(), it aims to treat references such as "post_parent"
* as full objects rather than IDs, making it possible to do $post->get_parent()->get_content().
*
* No caching has been added, but this would be trivial. Half written in pseudo-code and untested
*
*/
class Post {
var _id;
var _post;
function __construct( $post_id ) {
$this->_id = $post_id;
}
function get_id() {
return $this->_id;
}
function get_permalink() {
return get_permalink( $this->get_id() );
}
function get_title() {
return get_the_title( $this->get_id() );
}
function get_content() {
return get_the_content( $this->get_id() );
}
function get_parent() {
if( !$this->_post )
$this->_load_post();
return new Post( $this->_post->ID );
}
function get_excerpt( $length = 55 ) {
// Crap WP excerpt crap
}
function get_terms( $taxonomy ) {
return wp_get_object_terms( $taxonomy );
}
function get_meta( $key, $single = false ) {
return get_post_meta( $this->get_id(), $key, $single );
}
function get_author() {
if( !$this->_post )
$this->_load_post();
return get_userdata( $this->_post->post_author );
}
function get_featured_image( $size ) {
return get_the_post_thumbnail( $this->_id, $size );
}
function get_comments( $args = array() ) {
$args = wp_parse_args( $args );
$args['post_id'] = $this->get_id();
return get_comments( $args );
}
function _load_post() {
$this->_post = get_post( $this->_id );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment