2011-10-11 109 views
6

我想創建一個自定義類型的固定鏈接模式,包括其分類法之一。分類名稱從一開始就是已知的(所以我沒有試圖添加或混合它的所有分類法,只是一個特定的分類法),但是當然,價值將是動態的。WordPress的自定義類型固定鏈接包含分類學slu 012

通常情況下,自定義類型固定鏈接是使用rewrite參數與slug參數構建的,但我看不到我如何在其中添加動態變量。

http://codex.wordpress.org/Function_Reference/register_post_type

我猜需要定製的解決方案,但我不知道最好的非侵入方法是什麼。

是否有一個已知的做法,或有人最近建了類似的東西?我使用WP 3.2.1 btw。

回答

3

經過更多搜索,我設法使用custom_post_link過濾器創建了相當優雅的解決方案。

比方說,您有一個project自定義類型與client分類。添加這個鉤子:

function custom_post_link($post_link, $id = 0) 
{ 
    $post = get_post($id); 

    if(!is_object($post) || $post->post_type != 'project') 
    { 
    return $post_link; 
    } 
    $client = 'misc'; 

    if($terms = wp_get_object_terms($post->ID, 'client')) 
    { 
    $client = $terms[0]->slug; 

    //Replace the query var surrounded by % with the slug of 
    //the first taxonomy it belongs to. 
    return str_replace('%client%', $client, $post_link); 
    } 

    //If all else fails, just return the $post_link. 
    return $post_link; 
} 

add_filter('post_type_link', 'custom_post_link', 1, 3); 

然後,註冊自定義類型時,設置rewrite ARG這樣的:

'rewrite' => array('slug' => '%client%') 

我想我應該問之前已經扎得更深,但至少我們有一個完整的解決方案。

+0

謝謝!這對我有效。我必須確保我的'.htaccess'文件是可寫的,然後進入'Settings> Permalinks'和''Save Changes''以使其正常工作。 'add_filter('post_type_link','custom_post_link',1,3)中的'1'和'3'是什麼?再次感謝! –

+0

我以爲我有一切工作,但現在我得到了所有我的常規/非自定義帖子類型的帖子404錯誤。我發佈了一個關於這個問題,如果你有任何想法:http://stackoverflow.com/questions/9722984/wordpress-custom-permalink-with-dynamic-taxonomy-for-custom-post-type。 –

+0

強烈建議使用'get_the_terms'而不是'wp_get_object_terms',因爲'get_the_terms'會緩存結果。使用'wp_get_object_terms'將導致每次運行'post_link'過濾器時都會運行該查詢,這與Edit Post屏幕上的10次類似。 Ref https://core.trac.wordpress.org/browser/tags/3.9.1/src/wp-includes/category-template.php#L1238 – TomHarrigan

相關問題