wordpress create post type code example

Example 1: create custom post type with category in wordpress functions.php

function create_posttype() {
  register_post_type( 'wpll_product',
    array(
      'labels' => array(
        'name' => __( 'Products' ),
        'singular_name' => __( 'Product' )
      ),
      'public' => true,
      'has_archive' => true,
      'rewrite' => array('slug' => 'products'),
    )
  );
}
add_action( 'init', 'create_posttype' );

Example 2: wordpress register post type

function book_setup_post_type() {
    $args = array(
        'public'    => true,
        'label'     => __( 'Books', 'textdomain' ),
        'menu_icon' => 'dashicons-book',
    );
    register_post_type( 'book', $args );
}
add_action( 'init', 'book_setup_post_type' );

Example 3: how to store a single posttype in a plugin

/* Filter the single_template with our custom function*/
add_filter('single_template', 'my_custom_template');

function my_custom_template($single) {

    global $post;

    /* Checks for single template by post type */
    if ( $post->post_type == 'POST TYPE NAME' ) {
        if ( file_exists( PLUGIN_PATH . '/Custom_File.php' ) ) {
            return PLUGIN_PATH . '/Custom_File.php';
        }
    }

    return $single;

}

Tags:

Php Example