Easy steps (Snippet) for create custom post type or multiple post types

Just copy and paste below code into functions.php or into your custom plugins file and change according to your need..


Here i create two different post types "Story" and "Chapters" .

add_action( 'init', 'rj_custom_post_types' );
function rj_custom_post_types() {
    $cps = array();
    $cps['story'] = 'Story'; // add your custom post type here slug as key and name as value.
    $cps['chapter'] = 'Chapter';
    $icons = array('dashicons-media-interactive','dashicons-book');  // if you want to add icons then place icon slug here
    if(!empty($cps) && count($cps)>0)
    {
        $i = 0;
        foreach($cps as $key => $value)
        {
            $labels = array();
            $args = array();
            $labels = array(
        'name'               => _x( $value, 'post type general name', 'qode' ),
        'singular_name'      => _x( $value, 'post type singular name', 'qode' ),
        'menu_name'          => _x( str_replace('s','',(substr($value,'-1')=='y' ? rtrim($value, "y").'ie' : $value )).'s', 'admin menu', 'qode' ),
        'name_admin_bar'     => _x( $value, 'add new on admin bar', 'qode' ),
        'add_new'            => _x( 'Add New', $key, 'qode' ),
        'add_new_item'       => __( 'Add New '.$value, 'qode' ),
        'new_item'           => __( 'New '.$value, 'qode' ),
        'edit_item'          => __( 'Edit '.$value, 'qode' ),
        'view_item'          => __( 'View '.$value, 'qode' ),
        'all_items'          => __( 'All '.$value, 'qode' ),
        'search_items'       => __( 'Search '.$value.'s', 'qode' ),
        'parent_item_colon'  => __( 'Parent '.$value.':', 'qode' ),
        'not_found'          => __( 'No '.$value.'s found.', 'qode' ),
        'not_found_in_trash' => __( 'No '.$value.'s found in Trash.', 'qode' )
        );
        $args = array(
            'labels'             => $labels,
            'public'             => true,
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => true,
            'query_var'          => true,
            'rewrite'            => array( 'slug' => $key ),
            'capability_type'    => 'post',
            'has_archive'        => true,
            'hierarchical'       => true,
            'menu_position'      => null,
            'menu_icon'          => (isset($icons[$i]) ? $icons[$i] : ''),
            'supports'           => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments','page-attributes' )
        );
        register_post_type( $key, $args );
        $i++;
        }
    }
}

Comments

Popular posts from this blog

How to add a custom sorting or order by option on category archive or product archive page in woocommerce wordpress

How to create a custom wp_list_table and bulk action in wordpress

How to add image option in nav menu in wordpress