Wordpress向permalink自定义帖子类型添加分类标记
我现在正在搜索如何将分类添加到我的自定义帖子类型permalink的答案。我发现这篇文章几乎完全给出了答案,但它不适用于我的自定义帖子类型。 本文介绍了您首先进行的简单分类:Wordpress向permalink自定义帖子类型添加分类标记,wordpress,url-rewriting,taxonomy,Wordpress,Url Rewriting,Taxonomy,我现在正在搜索如何将分类添加到我的自定义帖子类型permalink的答案。我发现这篇文章几乎完全给出了答案,但它不适用于我的自定义帖子类型。 本文介绍了您首先进行的简单分类: add_action('init', 'my_rating_init'); function my_rating_init() { if (!is_taxonomy('rating')) { register_taxonomy( 'rating', 'post',
add_action('init', 'my_rating_init');
function my_rating_init() {
if (!is_taxonomy('rating')) {
register_taxonomy( 'rating', 'post',
array( 'hierarchical' => FALSE, 'label' => __('Rating'),
'public' => TRUE, 'show_ui' => TRUE,
'query_var' => 'rating',
'rewrite' => true ) );
}
}
然后你可以在Wordpress系统中重写url,比如:/%rating%/%postname%
然后,您需要通过执行以下操作将%rating%转换为分类标记:
add_filter('post_link', 'rating_permalink', 10, 3);
add_filter('post_type_link', 'rating_permalink', 10, 3);
function rating_permalink($permalink, $post_id, $leavename) {
if (strpos($permalink, '%rating%') === FALSE) return $permalink;
// Get post
$post = get_post($post_id);
if (!$post) return $permalink;
// Get taxonomy terms
$terms = wp_get_object_terms($post->ID, 'rating');
if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
else $taxonomy_slug = 'not-rated';
return str_replace('%rating%', $taxonomy_slug, $permalink);
}
这对“post”很有效,但当我更改时:
register_taxonomy( 'rating', 'post',
致:
URL重写不再有效。并且只提供以下url:
在我想要的地方:
所以我的两个问题是:
add_filter('post_link', 'modify_permalink', 10, 2);
add_filter('post_type_link', 'modify_permalink', 10, 2);
function modify_permalink($url, $post) {
// limit to certain post type. remove if not needed
if ($post->post_type != 'article') {
return $url;
}
// fetches post type to get slug for post type
$type = get_post_type_object($post->post_type);
// fetches term
$term = get_the_terms($post->ID, 'rating');
if ($term && count($term)) {
// takes only 1st one
$term = array_pop($term);
// creates the url prepending post type slug and term slug to post name
$url = site_url('/').($type->rewrite ? $type->rewrite['slug'].'/' : '' ).$term->slug.'/'.$post->post_name;
}
return $url;
}
然后必须添加自定义url重写。如前所述
add_filter('post_link', 'modify_permalink', 10, 2);
add_filter('post_type_link', 'modify_permalink', 10, 2);
function modify_permalink($url, $post) {
// limit to certain post type. remove if not needed
if ($post->post_type != 'article') {
return $url;
}
// fetches post type to get slug for post type
$type = get_post_type_object($post->post_type);
// fetches term
$term = get_the_terms($post->ID, 'rating');
if ($term && count($term)) {
// takes only 1st one
$term = array_pop($term);
// creates the url prepending post type slug and term slug to post name
$url = site_url('/').($type->rewrite ? $type->rewrite['slug'].'/' : '' ).$term->slug.'/'.$post->post_name;
}
return $url;
}