Fam Wencong, Kenneth

My Diary

How To Create Custom Post Types In WordPress

Published: Wednesday, January 29, 2020

WordPress comes with five default post types: post, page, attachment, revision, menu.

While developing your own theme or plugin, you may need to create your own specific content type: for example, products for an e-commerce website, assignments for an e-learning website, or movies for a review website.

Using Custom Post Types, you can register your own post type. Once a post type is registered, it gets a new top-level administrative screen that can be used to manage and create posts of that type.

To register a new post type, you use the register_post_type() function.

The following creates a new post type called book.

class MyClass {
    public static function register_post_type() {
          $args = array(
            'public' => true,
            'label' => 'Books',
            'show_in_menu' => true,
            'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
          );
          register_post_type( 'book', $args );       
    }
}

add_action( 'init', array('MyClass', 'register_post_type') );

Once created, the new post-type would have its own menu in the WordPress dashboard admin area. You can also create multiple post type as well such as Movies, Portfolio, and much more.

To get these posts in The Loop, you query the ‘ post_type’ key. Modify the following code to suite your needs.

$loop = new WP_Query(array(  
    'post_type' => 'book',
    'post_status' => 'publish',
    'posts_per_page' => 10, 
)); 
    
while ( $loop->have_posts() ) : $loop->the_post(); 
    the_excerpt(); 
endwhile;

wp_reset_postdata();