几乎直接从advanced taxonomies with pretty urls 上的这篇优秀文章中提取了这一点。
首先创建一些新的重写规则。这可能应该在特定于站点的 sn-ps 插件中,而不是在您的主题中。然后转到永久链接并重新保存您的永久链接。
function so_25722819_add_rewrite_rules() {
global $wp_rewrite;
$new_rules = array(
'event/(industry|location)/(.+?)/(industry|location)/(.+?)/?$' => 'index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2) . '&' . $wp_rewrite->preg_index(3) . '=' . $wp_rewrite->preg_index(4),
'event/(industry|location)/(.+)/?$' => 'index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2)
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'so_25722819_add_rewrite_rules' );
现在,如果您使用 url 访问您的网站:
www.example.com/auto/my_auto/ricambio/my_ricambio
您应该转到显示相同结果的分类存档页面:
www.example.com/?auto=my_auto&ricambio=my_ricambio
要回显这些漂亮的固定链接,您可以使用文章作者提供的插件,只需稍作调整即可从他的eg_events 帖子类型切换到您的product 帖子类型。
function eg_get_filter_permalink( $taxonomy_slug, $term ) {
global $wp_query;
// If there is already a filter running for this taxonomy
if( isset( $wp_query->query_vars[$taxonomy_slug] ) ){
// And the term for this URL is not already being used to filter the taxonomy
if( strpos( $wp_query->query_vars[$taxonomy_slug], $term ) === false ) {
// Append the term
$filter_query = $taxonomy_slug . '/' . $wp_query->query_vars[$taxonomy_slug] . '+' . $term;
} else {
// Otherwise, remove the term
if( $wp_query->query_vars[$taxonomy_slug] == $term ) {
$filter_query = '';
} else {
$filter = str_replace( $term, '', $wp_query->query_vars[$taxonomy_slug] );
// Remove any residual + symbols left behind
$filter = str_replace( '++', '+', $filter );
$filter = preg_replace( '/(^\+|\+$)/', '', $filter );
$filter_query = $taxonomy_slug . '/' . $filter;
}
}
} else {
$filter_query = $taxonomy_slug . '/' . $term;
}
// Maintain the filters for other taxonomies
if( isset( $wp_query->tax_query ) ) {
foreach( $wp_query->tax_query->queries as $query ) {
$tax = get_taxonomy( $query['taxonomy'] );
// Have we already handled this taxonomy?
if( $tax->query_var == $taxonomy_slug )
continue;
// Make sure taxonomy hasn't already been added to query string
if( strpos( $existing_query, $tax->query_var ) === false )
$existing_query .= $tax->query_var . '/' . $wp_query->query_vars[$tax->query_var] . '/';
}
}
if( isset( $existing_query ) )
$filter_query = $existing_query . $filter_query;
return trailingslashit( get_post_type_archive_link( 'product' ) . $filter_query );
}
然后在任何模板中,您都可以使用上述函数为您的多个分类归档生成漂亮的永久链接:
// Link to page with only my_ricambio in my_auto
echo eg_get_filter_permalink( 'my_auto', 'my_ricambio' );