Custom Post Types

Jon Bishop
June 25, 2012

http://www.jonbishop.com/cpt.zip

What Are Custom Post Types

When Should I Use Them?

Anywhere you need a new content type

Creating New Post Types

<?php
add_action( 'init', 'create_post_type' );
function create_post_type() {
	register_post_type( 'my-post-type',
		array(
			'labels' => array(
				'name' => __( 'My Post Type' ),
				'singular_name' => __( 'My Post Type' )
			),
		'public' => true,
		'has_archive' => true,
		)
	);
}
?>
http://codex.wordpress.org/Post_Types

Querying by Post Type

<?php
$args = array( 'post_type' => 'my-post-type', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
	the_title();
	echo '<div class="entry-content">';
	the_content();
	echo '</div>';
endwhile;
?>
http://codex.wordpress.org/Post_Types

Using Custom Post Types

Getting the post type of a post

<?php
$post_type = get_post_type( $post_id );
?>

Checking if a post type exists

<?php
if ( is_post_type( 'my-post-type' ) )
?>
Source: http://justintadlock.com/archives/2010/04/29/custom-post-types-in-wordpress

Modifying Custom Post Types

Remove support of certain features for a given post type

<?php
add_action('init', 'my_custom_init');
function my_custom_init() {
	add_post_type_support( 'my-post-type', 'author' );
        remove_post_type_support( 'my-post-type', 'excerpt' );
}
?>

Checks a post type’s support for a given feature.

<?php
post_type_supports( 'my-post-type', 'editor' )
?>
http://codex.wordpress.org/Function_Reference/add_post_type_support
http://codex.wordpress.org/Function_Reference/remove_post_type_support
http://codex.wordpress.org/Function_Reference/post_type_supports

Custom Post Type Templates

Custom Post Types display

Custom Taxonomies display

Stuff To Remember

Execute flush_rewrite_rules with register_activation_hook to make pemerlinks work with your new post type

Prefix your name with a short “namespace” so you don’t conflict with other theme’s and plugins

http://codex.wordpress.org/Function_Reference/register_post_type
http://codex.wordpress.org/Custom_Post_Types

Thanks!

Jon Bishop
Web Developer @ AMP Agency

Website / JonBishop.com
Twitter / @JonDBishop