Title

PHP Custom Post Via Code & Plugin

description

How to make a custom post. Easy interface with CPT UI, or with a simple code snippet.

Published 2022-05-04

Modified 2022-12-07

content

				
					// Add custom post type

function rp_books_register_post_type() {

//UI Visible labels
$labels = array(
 'name' => __( 'Books', 'rp' ),
 'singular_name' => __( 'Book', 'rp' ),
 'add_new' => __( 'New Book', 'rp' ),
 'add_new_item' => __( 'Add New Book', 'rp' ),
 'edit_item' => __( 'Edit Book', 'rp' ),
 'new_item' => __( 'New Book', 'rp' ),
 'view_item' => __( 'View Book', 'rp' ),
 'search_items' => __( 'Search Books', 'rp' ),
 'not_found' =>  __( 'No Books Found', 'rp' ),
 'not_found_in_trash' => __( 'No Books Found in Trash', 'rp' ),
);

// Post functionality
$args = array(
  'labels' => $labels,
  'has_archive' => 'books',
//'has_archive' => true,
  'menu_icon'   => 'dashicons-dashboard',
  'public' => true,
  'hierarchical' => false,
  'supports' => array(
    'title',
    'editor',
    'excerpt',
    'custom-fields',
    'thumbnail',
    'page-attributes'
  ),
//'taxonomies' => 'category',
  'rewrite'   => array( 'slug' => 'book' ),
  'show_in_rest' => true
  //false by default:
  //'show_admin_column' => true,
);

register_post_type( 'rp_book', $args );
	
}
add_action( 'init', 'rp_books_register_post_type' );
				
			
				
					// Add custom taxonomy to default or custom posts

function create_themes() {
    $labels = array(
        'name' => _x('Themes', 'taxonomy general name'),
        'singular_name' => _x('Theme', 'taxonomy singular name'),
        'search_items' => __('Zoek'),
        'all_items' => __('Al'),
        'parent_item' => __('Parent'),
        'parent_item_colon' => __('Parent Location:'),
        'edit_item' => __('Edit'),
        'update_item' => __('Update'),
        'add_new_item' => __('New'),
        'new_item_name' => __('New Theme'),
    );

// For standard posts:
    register_taxonomy('themes', 'post', array(
        'hierarchical' => true,
        'labels' => $labels
    ));


// For custom posts:
    register_taxonomy('themes', 'rp_book', array(
        'hierarchical' => true,
        'labels' => $labels
    ));

}

add_action('init', 'create_themes');