I have registered the custom post type “word” and the custom taxonomy “wordcat”.
Now what I want is proper hierarchical permalinks. So I’ve been searching the web for quite some time with no result.
No matter what I try I can’t get WORKING hierarchical permalinks. WordPress won’t find the post page.
Here is my code :
Custom Post Type
function create_word_post_types() {
$args = array(
'labels' => $labels,
'public' => true,
'menu_position' => 25,
'rewrite' => array( 'slug' => 'word/%wordcat%'),
'query_var' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'revisions'
),
'has_archive' => false
);
register_post_type( 'word', $args );
}
add_action( 'init', 'create_word_post_types' );
Custom Taxonomy
function word_taxonomy() {
$args = array(
'labels' => $labels,
'hierarchical' => true,
'query_var' => true,
'rewrite' => array( 'hierarchical' => true, 'slug' => 'word')
);
register_taxonomy( 'word-categories', 'word', $args );
}
add_action( 'init', 'word_taxonomy', 0 );
Rewrite rules
based on this link:
How to create a permalink structure with custom taxonomies and custom post types like base-name/parent-tax/child-tax/custom-post-type-name
add_filter('rewrite_rules_array', 'mmp_rewrite_rules');
function mmp_rewrite_rules($rules) {
$newRules = array();
$newRules['word/(.+)/(.+)/(.+)/(.+)/?$'] = 'index.php?word=$matches[4]';
$newRules['word/(.+)/?$'] = 'index.php?word-categories=$matches[1]';
return array_merge($newRules, $rules);
}
function filter_post_type_link($link, $post)
{
if ($post->post_type != 'word')
return $link;
if ($cats = get_the_terms($post->ID, 'word-categories'))
{
$link = str_replace('%wordcat%', get_taxonomy_parents(array_pop($cats)->term_id, 'word-categories', false, '/', true), $link);
}
return $link;
}
add_filter('post_type_link', 'filter_post_type_link', 10, 2);
function get_taxonomy_parents($id, $taxonomy, $link = false, $separator = '/', $nicename = false, $visited = array()) {
$chain = '';
$parent = &get_term($id, $taxonomy);
if (is_wp_error($parent)) {
return $parent;
}
if ($nicename)
$name = $parent -> slug;
else
$name = $parent -> name;
if ($parent -> parent && ($parent -> parent != $parent -> term_id) && !in_array($parent -> parent, $visited)) {
$visited[] = $parent -> parent;
$chain .= get_taxonomy_parents($parent -> parent, $taxonomy, $link, $separator, $nicename, $visited);
}
if ($link) {
// nothing, can't get this working :(
} else
$chain .= $name . $separator;
return $chain;
}
The result looks correct :
www.mysite.com/word/adjective/annoying/
but doesn’t display the post. Instead i get the dreaded 404 error.