Skip to content

Instantly share code, notes, and snippets.

@iworks
Created March 11, 2022 13:05
Show Gist options
  • Save iworks/7aab3fd0b1f3e40a758cf13ed00c0858 to your computer and use it in GitHub Desktop.
Save iworks/7aab3fd0b1f3e40a758cf13ed00c0858 to your computer and use it in GitHub Desktop.
WordPress - custom post type - book
<?php
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'book',
array(
'labels' => array(
'name' => __( 'Books', 'book-post-type' ),
'singular_name' => __( 'Book', 'book-post-type' )
),
'public' => true,
'has_archive' => __( 'book-archive', 'book-post-type' ),
'publicly_queryable' => true,
'exclude_from_search' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_rest' => false,
'query_var' => true,
'rewrite' => array('slug' => _x( 'book', 'URL slug', 'book-post-type' )),
'supports' =>array('title','editor', 'custom-fields','thumbnail', 'revisions')
)
);
register_taxonomy( 'publisher', 'book', array( 'labels' => array( 'name' => 'Publisher' ) ) );
register_taxonomy( 'country', 'book', array( 'hierarchical' => true, 'labels' => array( 'name' => 'Country' ) ) );
register_taxonomy_for_object_type( 'category', 'book' );
}
add_action( 'pre_get_posts', function( $wp_query ) {
if ( ! $wp_query->is_main_query() ) {
return;
}
if ( $wp_query->is_category() ) {
$wp_query->set( 'posts_per_page', 1 );
$wp_query->set( 'post_type', array( 'post', 'book', ) );
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment