2014-05-16 62 views
18

我試圖創建一個自定義的固定鏈接結構,這將允許我完成以下操作。自定義的固定鏈接結構:/%自定義的固定鏈接類型的%/%自定義的分類%/%後名稱%/

  1. 我有一個自定義職位類型,稱爲「項目」
  2. 我有一個名爲分配到CPT「項目類別」,「項目」

我想我的永久鏈接結構的自定義分類看起來是這樣的:

項目/分類/項目名稱

/%custom-post-type%/%custom-taxonomy%/%post-name%/

我已經能夠成功地使用/%category%/在永久鏈接中進行正常的,out-of-框中的WP帖子,但不適用於CPT。

如何創建這樣的永久鏈接結構會影響URL或其他頁面?是否可以定義自定義永久鏈接結構並將其限制爲單個CPT?

感謝

+2

這個插件能解決你的問題嗎? https://wordpress.org/plugins/custom-post-type-permalinks/ –

+0

我總是猶豫使用太多的插件,但我會定義嘗試一下!謝謝。 –

+0

我完全同意你的看法,儘管最近我對真正基本的插件有點寬鬆,基本上只是從我們身上採取了一些咕嚕聲。希望能爲你解決問題! –

回答

18

幸運的是,我剛爲客戶的項目做到這一點。我用this answer on the WordPress Stackexchange作爲指導:

/** 
* Tell WordPress how to interpret our project URL structure 
* 
* @param array $rules Existing rewrite rules 
* @return array 
*/ 
function so23698827_add_rewrite_rules($rules) { 
    $new = array(); 
    $new['projects/([^/]+)/(.+)/?$'] = 'index.php?cpt_project=$matches[2]'; 
    $new['projects/(.+)/?$'] = 'index.php?cpt_project_category=$matches[1]'; 

    return array_merge($new, $rules); // Ensure our rules come first 
} 
add_filter('rewrite_rules_array', 'so23698827_add_rewrite_rules'); 

/** 
* Handle the '%project_category%' URL placeholder 
* 
* @param str $link The link to the post 
* @param WP_Post object $post The post object 
* @return str 
*/ 
function so23698827_filter_post_type_link($link, $post) { 
    if ($post->post_type == 'cpt_project') { 
    if ($cats = get_the_terms($post->ID, 'cpt_project_category')) { 
     $link = str_replace('%project_category%', current($cats)->slug, $link); 
    } 
    } 
    return $link; 
} 
add_filter('post_type_link', 'so23698827_filter_post_type_link', 10, 2); 

在註冊自定義後類型和分類,一定要使用以下設置:

// Used for registering cpt_project custom post type 
$post_type_args = array(
    'rewrite' => array(
    'slug' => 'projects/%project_category%', 
    'with_front' => true 
) 
); 

// Some of the args being passed to register_taxonomy() for 'cpt_project_category' 
$taxonomy_args = array(
    'rewrite' => array(
    'slug' => 'projects', 
    'with_front' => true 
) 
); 

當然,一定要刷新重寫規則,當你」重做。祝你好運!

+0

非常好,謝謝!我很匆忙,所以我不得不依賴一個插件(我不喜歡這樣做)來快速完成它。我將在未來的項目中實現這一點! –

+1

你有沒有試圖讓這個與子類別一起工作,或者知道我可以如何使它與子類別一起工作? – Jordan

+0

這工作;然而,'get_post_type_archive_link('projects')'在url中使用'%project_catgory%'返回,因爲slug是用它定義的。 – Seed

相關問題