[英]Wordpress Add Taxonomy tag to permalink custom post type
我現在正在尋找如何將分類法添加到我的自定義帖子類型永久鏈接的答案。 我發現這篇文章幾乎可以給出答案,但不適用於我的自定義帖子類型。 http://shibashake.com/wordpress-theme/add-custom-taxonomy-tags-to-your-wordpress-permalinks
本文介紹您首先進行一個簡單的分類法:
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系統中重寫網址,例如:/%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);
}
這適用於“發布”,但是當我更改時:
register_taxonomy( 'rating', 'post',
至:
register_taxonomy( 'rating', 'mycustomposttype',
URL重寫不再起作用。 並且僅提供以下網址:
http://www.website.com/custom-post-type/post
我想在哪里:
http://www.website.com/custom-post-type/taxonomy-tag/post
所以我的兩個問題是:
這樣嘗試
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;
}
然后,您必須添加自定義網址重寫。 正如在WordPress網站上的解釋
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.