我需要创建一个自定义permalink结构,我想在url中显示m自定义分类法,类似于:
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\');
要将自定义分类添加到url,我已编辑了permalink结构,如下所示:
/%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 );
使用此代码,我可以创建链接。
问题是,如果我创建一个假url,如:
www.example.com/ristoranti/XXXXX/XXXX/my-post-slug
我可以看到帖子,而XXXX/XXX
完全错了。
这怎么可能?如何确保url中的分类法是正确的?