我发现this 链接太有用了。这是我迄今为止编写的代码,它适用于除两个场景之外的所有场景。
register_post_type( \'article\',
array(
\'labels\' => array(
\'name\' => \'Article\',
\'singular_name\' => \'Article\',
\'add_new\' => \'Add Article\',
\'add_new_item\' => \'Add New Article\',
\'edit\' => \'Edit\',
\'edit_item\' => \'Edit Article\',
\'new_item\' => \'New Article\',
\'view\' => \'View\',
\'view_item\' => \'View Article\',
\'search_items\' => \'Search Article\',
\'not_found\' => \'No Article\',
\'not_found_in_trash\' => \'No Post found in Article\',
\'parent\' => \'Parent Article\'
),
\'public\' => true,
\'hierarchical\' => true,
\'menu_position\' => 15,
\'supports\' => array( \'title\', \'editor\', \'comments\', \'thumbnail\' ),
\'taxonomies\' => array( \'\' ),
\'menu_icon\' => get_template_directory_uri().\'/img/icon_article.png\',
\'query_var\' => true,
\'rewrite\' => array(
\'slug\' => \'articles/%article_category%\',
\'with_front\' => true
),
\'has_archive\' => \'articles\',
\'register_meta_box_cb\' => \'add_article_metaboxes\'
)
);
register_taxonomy(\'article_category\',\'article\',array(
\'hierarchical\' => true,
\'labels\' => $labels,
\'query_var\' => true,
\'rewrite\' => array(\'slug\' => \'articles\', \'hierarchical\' => true),
));
add_filter(\'rewrite_rules_array\', \'mmp_rewrite_rules\');
function mmp_rewrite_rules($rules) {
$newRules = array();
$newRules[\'articles/(.+)/(.+)/(.+)/?$\'] = \'index.php?article=$matches[3]\';
$newRules[\'articles/(.+)/(.+)/?$\'] = \'index.php?article=$matches[2]\';
$newRules[\'articles/(.+)/?$\'] = \'index.php?article_category=$matches[1]\';
return array_merge($newRules, $rules);
}
function filter_post_type_link($link, $post)
{
if ($post->post_type != \'article\')
return $link;
if ($cats = get_the_terms($post->ID, \'article_category\'))
{
$link = str_replace(\'%article_category%\', get_taxonomy_parents(array_pop($cats)->term_id, \'article_category\', false, \'/\', true), $link); // see custom function defined below
}
return $link;
}
add_filter(\'post_type_link\', \'filter_post_type_link\', 10, 2);
// my own function to do what get_category_parents does for other taxonomies
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;
}
但这种解决方案在两种情况下都不起作用。
第一种情况:在子分类法上直接链接,例如:sitename。com/articles/parenttax/childtax/
第二种情况:对自定义贴子页面进行分页,例如:sitename。com/articles/parenttax/childtax/postname/page/2
我是否必须为它们创建单独的函数,还是只需要为其添加新规则?