Reputation: 1008
I need a post type to be the child of a page (actually of basically any other post type and itself), and it must apply to the CPT's taxonomies as well.
The general idea is to have a dynamic parent page in my options saved under cpt_parent_page
. Currently, my slug works out fine; in the admin, under my CPT taxomomies, I have the right links. However, when I view the taxonomy, I'm getting a 404. I'm pretty sure I'm just forgetting a very minor thing, but I need to remember said thing.
$cpt = 'book';
$cpt_singular = 'Book';
$cpt_plurial = 'Books';
/*
* Register CPT
*/
$labels = array(
'add_new_item' => 'Add New '.$cpt_singular,
'all_items' => 'All '.$cpt_plurial,
'edit_item' => 'Edit '.$cpt_singular,
'name' => $cpt_singular,
'name_admin_bar' => $cpt_singular,
'new_item' => 'New '.$cpt_singular,
'not_found' => 'No '.$cpt_singular.' found',
'not_found_in_trash' => 'No '.$cpt_plurial.' found in Trash',
'parent_item_colon' => 'Parent '.$cpt_singular,
'search_items' => 'Search '.$cpt_plurial,
'view_item' => 'View '.$cpt_singular,
'view_items' => 'View '.$cpt_plurial,
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'can_export' => true,
'has_archive' => false,
'hierarchical' => true,
'menu_position' => null,
'supports' => array( 'editor', 'thumbnail', 'title' ),
'rewrite' => array(
'slug' => get_permalink( get_option('cpt_parent_page') ),
'with_front' => false
),
);
register_post_type($cpt, $args);
/*
* Register taxonomy
*/
register_taxonomy(
$cpt_name, // Taxonomy name
$cpt, // Associate taxonomy to this post type
array(
'hierarchical' => true,
'label' => $tax_name,
'query_var' => true,
'rewrite' => array(
'slug' => get_permalink( get_option('cpt_parent_page') ),
'with_front' => false
),
'show_in_quick_edit' => true,
'show_admin_column' => true,
)
);
Upvotes: 1
Views: 1614
Reputation: 15620
You got the error 404
most likely because you haven't flushed the rewrite rules after you changed the option. But even if that's not the case, make certain to always flush the rules after the option is changed — simply visit the permalink settings page.
In addition to that, you shouldn't use get_permalink()
, or that you should use the post slug and not its permalink URL. So make the following changes:
// Change this:
get_permalink( get_option('cpt_parent_page') )
// to this FOR THE POST TYPE:
get_post_field( 'post_name', get_option('cpt_parent_page') ) . '/p'
// or this FOR THE TAXONOMY:
get_post_field( 'post_name', get_option('cpt_parent_page') ) . '/t'
That should work; however, the /p
and /t
are necessary so that WordPress knows if the request is for a post or term (in a taxonomy) — without the /p
or /t
, the rewrite rules will clash and likely fail (e.g. a term request is confused as being a post or child Page request).
Upvotes: 2