开发者 | misterbisson |
---|---|
更新时间 | 2012年8月13日 10:58 |
PHP版本: | 3.3 及以上 |
WordPress版本: | 3.4.1 |
register_post_types
action. The function defines a class for your post type that extends the GO_Cpt
class. This follows a design pattern established by the modern widgets API (as introduced in WP 2.8) http://codex.wordpress.org/Widgets_API#Developing_Widgets .
The result is a new custom post type and much easier creation and updating of custom meta associated with that post type. You'll also have a convenient object you can use to access the metadata associated with each post.
`
function my_customposttype()
{
class My_CustomPostType extends GO_Cpt
{
function __construct()
{
// execute the parent constructor with the name
// and definition for the custom post type
parent::__construct( $post_type_name , $post_type_definition );
}
function metabox( $post , $meta )
{
// print out the form here
//
// this method is optional, only use it if you want to
// add a metabox to your custom post type
}
function update( $new_meta , $old_meta )
{
// sanitize and validate the metadata
// then return $meta so it can be saved
//
// this method is required if a
// metabox() method is included
}
}
global $my_customposttype;
$my_customposttype = new My_CustomPostType;
}
// hook that function to the register_post_types action
add_action( 'register_post_types' , 'my_customposttype' );
`
Backstory: defining the post type class inside the function avoids issues with loading order and fatal errors resulting from attempting to extend a class that might not exist yet. Isn't PHP awesome?
See the included hello world example: http://plugins.trac.wordpress.org/browser/go-cptfactory/trunk/example-helloworld-cpt.php
To access the meta associated with a post, you can call $my_customposttype->get_meta( $post_id );
You can easily add a method and hook to filter the_content
or the_excerpt
to insert custom values that may have been entered in the post meta. Simply add add_filter( 'the_content' , array( $this , 'the_content' ));
in the __construct()
and then define another method in the My_CustomPostType
class such as:`
function the_content( $content )
{
$meta_print = print_r( $this->get_meta( get_the_ID() ) , TRUE );
return $meta_print . $content
}
`
wp-content/plugins/
directory and activate it.A: You should consinder Pods: http://podsframework.org
A: Pods is cool, but this keeps the problem in code, without any dependency on configuration information stored in the database. This also fits the architecture I like where the code related to a post type is associated with the post type definition. In my use, custom post type classes actually have many more methods to collect, validate, and display their data.