Skip to content

Instantly share code, notes, and snippets.

@sohelamin
Created April 3, 2019 19:47
Show Gist options
  • Save sohelamin/d2f5216f4e321d643aef230828d8b879 to your computer and use it in GitHub Desktop.
Save sohelamin/d2f5216f4e321d643aef230828d8b879 to your computer and use it in GitHub Desktop.
WordPress custom post type taxonomy (book/taxonomy-name/page/2)
<?php
add_action( 'init', 'codex_book_init' );
function codex_book_init() {
$labels = array(
'name' => _x( 'Books', 'post type general name', 'your-plugin-textdomain' ),
'singular_name' => _x( 'Book', 'post type singular name', 'your-plugin-textdomain' ),
'menu_name' => _x( 'Books', 'admin menu', 'your-plugin-textdomain' ),
'name_admin_bar' => _x( 'Book', 'add new on admin bar', 'your-plugin-textdomain' ),
'add_new' => _x( 'Add New', 'book', 'your-plugin-textdomain' ),
'add_new_item' => __( 'Add New Book', 'your-plugin-textdomain' ),
'new_item' => __( 'New Book', 'your-plugin-textdomain' ),
'edit_item' => __( 'Edit Book', 'your-plugin-textdomain' ),
'view_item' => __( 'View Book', 'your-plugin-textdomain' ),
'all_items' => __( 'All Books', 'your-plugin-textdomain' ),
'search_items' => __( 'Search Books', 'your-plugin-textdomain' ),
'parent_item_colon' => __( 'Parent Books:', 'your-plugin-textdomain' ),
'not_found' => __( 'No books found.', 'your-plugin-textdomain' ),
'not_found_in_trash' => __( 'No books found in Trash.', 'your-plugin-textdomain' )
);
$args = array(
'labels' => $labels,
'description' => __( 'Description.', 'your-plugin-textdomain' ),
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array( 'slug' => 'book/%genre%' ),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
);
register_post_type( 'book', $args );
register_taxonomy(
'genre',
'book',
array(
'label' => __( 'Genre' ),
'rewrite' => array( 'slug' => 'genre' ),
'hierarchical' => true,
)
);
}
add_filter( 'post_type_link', function ( $post_link, $post ) {
$terms = wp_get_object_terms( $post->ID, 'genre' );
if ( $terms ) {
return str_replace( '%genre%' , $terms[0]->slug , $post_link );
} else {
return str_replace( '%genre%/' , '' , $post_link );
}
return $post_link;
}, 1, 2 );
add_filter('init', function() {
add_rewrite_rule(
'^book/([^/]*)/([^/]*)/(\d*)?',
'index.php?genre=$matches[1]&p=$matches[2]&paged=$matches[3]',
'top'
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment