我真的被困在那里了 . 我为我的客户编写了一个自定义主题,其自定义帖子类型名为“urunler”,自定义taxanomy名为“urun-kategori” . 我的客户想要像以下网址:
sitename/custom-taxonomy/custom-post-type-post-name
要存档,首先我删除了自定义分类标本:
add_filter('request', 'rudr_change_term_request', 1, 1 );
function rudr_change_term_request($query){
$tax_name = 'urun-kategori'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'
// Request for child terms differs, we should make an additional check
if( $query['attachment'] ) :
$include_children = true;
$name = $query['attachment'];
else:
$include_children = false;
$name = $query['name'];
endif;
$term = get_term_by('slug', $name, $tax_name); // get the current term to make sure it exists
if (isset($name) && $term && !is_wp_error($term)): // check it here
if( $include_children ) {
unset($query['attachment']);
$parent = $term->parent;
while( $parent ) {
$parent_term = get_term( $parent, $tax_name);
$name = $parent_term->slug . '/' . $name;
$parent = $parent_term->parent;
}
} else {
unset($query['name']);
}
switch( $tax_name ):
case 'category':{
$query['category_name'] = $name; // for categories
break;
}
case 'post_tag':{
$query['tag'] = $name; // for post tags
break;
}
default:{
$query[$tax_name] = $name; // for another taxonomies
break;
}
endswitch;
endif;
return $query;}
add_filter( 'term_link', 'rudr_term_permalink', 10, 3 );
function rudr_term_permalink( $url, $term, $taxonomy ){
$taxonomy_name = 'urun-kategori'; // your taxonomy name here
$taxonomy_slug = 'urun-kategori'; // the taxonomy slug can be different with the taxonomy name (like 'post_tag' and 'tag' )
// exit the function if taxonomy slug is not in URL
if ( strpos($url, $taxonomy_slug) === FALSE || $taxonomy != $taxonomy_name ) return $url;
$url = str_replace('/' . $taxonomy_slug, '', $url);
return $url;
}
并添加到我的帖子网址:
function add_tax_support($url) {
$terms = wp_get_object_terms( get_the_ID(), 'urun-kategori', array( 'fields' => 'slugs' ) );
if(!empty($terms)){
$taxurl = implode('/', $terms );
return str_replace('%urun-kategori%', $taxurl, $url);
}
}
add_filter('post_type_link', 'add_tax_support');
现在我的自定义帖子的永久链接看起来像:
sitename/urunler/urun-kategori/postname
当我试图删除那个“urunler”自定义帖子类型slug时,我遇到了2个错误:1)成功删除了csutom post类型slug,为url添加了自定义分类,并且自定义永久链接按预期工作;但其他帖子和页面(wordpress默认值)获得404错误 . 在自定义帖子类型设置中:
$rewrite = array(
'slug' => '%urun-kategori%',
'with_front' => false,
'hierarchical' => false );
2)所有的wordpress链接都有效,但自定义的帖子类型slug仍然存在,这对我没用 . 在自定义帖子类型设置中:
$rewrite = array(
'slug' => 'urunler/%urun-kategori%',
'with_front' => false,
'hierarchical' => false );
此外,当我尝试使用str_replace删除“urunler”slug时,自定义帖子网址无法正常工作 .
我知道这太过分了,但我真的被卡住了 . 希望有人可以帮助我 .