问题
I'm trying to set a custom permalink structure for a custom post type based on a custom parent/child taxonomy. I've managed to achieve the thing but I broke the permalink structure for pages and posts.
I've accomplisged the following:
mysite.com/taxonomy_parent/taxonomy_child/postname
In other words, I've remove the taxonomy slug and the URL show the correct hierarchical order. First, I set the 'rewrite' arg when registering the custom taxonomy and the custom post-type:
for the custom taxonomy:
'rewrite' => array( 'slug' => '', 'with_front' => false, 'hierarchical' => true ),
for the post type:
'rewrite' => array( 'slug' => '%mytaxonomy%', 'with_front' => false, 'hierarchical' => true ),
Then I added the following code in order to get support to show the parent/child taxonomy in the URL.
add_filter('rewrite_rules_array', 'mmp_rewrite_rules');
function mmp_rewrite_rules($rules) {
$newRules = array();
$newRules['(.+)/(.+)/(.+)/?$'] = 'index.php?myposttype=$matches[3]';
$newRules['(.+)/?$'] = 'index.php?mytaxonomy=$matches[1]';
return array_merge($newRules, $rules);
}
function filter_post_type_link($link, $post)
{
if ($post->post_type != 'myposttype')
return $link;
if ($cats = get_the_terms($post->ID, 'mytaxonomy'))
{
$link = str_replace('%mytaxonomy%', get_taxonomy_parents(array_pop($cats)->term_id, 'mytaxonomy', 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;
}
This works great but there's a conflict with the custom permalink for the posts and pages. I need to configure that too. Actually, I need "mysite.com/blog/category/postname" and "mysite.com/pagename". As easy as to set a custom permalink like that "/%category%/%postname%/" works properly but a 404 error page is returned when the necessary current config I've explained is set in my functions.php
I suppose there's a problem with rewrite_rules but don't know how to fix it or how to set new rules to support my custom post_type/custom taxonomy permalink structure at the same time the custom permalink structure for posts and pages works properly.
来源:https://stackoverflow.com/questions/9263407/wordpress-custom-permalink-structure-for-pages-posts-and-custom-post-types