我需要创建一个自定义固定链接结构,我想在网址中显示自定义分类,如:
www.example.com/ristoranti/italia/milano/my-post-slug
第一段是帖子类别,添加了WP Categories菜单
italia
和milano
是使用自定义插件创建的分类法,其中milano
是italia
的孩子:
function mlt_create_custom_taxonomies()
{
$labels = [
'name' => _x( 'Locations', 'taxonomy general name', 'mlt' ),
'singular_name' => _x( 'Location', 'taxonomy singular name', 'mlt' ),
'search_items' => __( 'Search Locations', 'mlt' ),
'all_items' => __( 'All Locations', 'mlt' ),
'parent_item' => __( 'Parent Location', 'mlt' ),
'parent_item_colon' => __( 'Parent Location:', 'mlt' ),
'edit_item' => __( 'Edit Location', 'mlt' ),
'update_item' => __( 'Update Location', 'mlt' ),
'add_new_item' => __( 'Add New Location', 'mlt' ),
'new_item_name' => __( 'New Location Name', 'mlt' ),
'menu_name' => __( 'Location', 'mlt' ),
];
$args = [
'labels' => $labels,
'exclude_from_search' => true,
'has_archive' => true,
'hierarchical' => true,
'rewrite' => array( 'with_front' => false, 'hierarchical' => true, ),
'show_ui' => true,
'show_tagcloud' => false,
];
register_taxonomy( 'location', [ 'post' ], $args );
}
add_action('init', 'mlt_create_custom_taxonomies');
要将自定义分类法添加到网址,我已经编辑了我的永久链接结构:
/%category%/%location%/%postname%/
我还为%location%
添加了重写规则,以便添加分类法:
function location_post_type_link( $link, $post ) {
if ('post' == $post->post_type) {
if ( $terms = get_the_terms( $post->ID, 'location' ) ) {
foreach ($terms as $term) {
$tax_array[] = $term->slug;
}
$link = str_replace( '%location%', implode('/',$tax_array), $link );
}
}
return $link;
}
add_filter( 'post_link', 'location_post_type_link', 10, 2 );
使用此代码,我可以创建链接。
问题是,如果我创建一个假的网址:
www.example.com/ristoranti/XXXXX/XXXX/my-post-slug
我能够看到帖子,而XXXX/XXX
完全错误。
这怎么可能?如何确保网址中的分类正确?