2011-09-19 58 views
-1

我非常喜歡Custom Post Templates插件,所以我想將其構建到我的主題中。在WordPress中爲帖子添加自定義函數?

函數can be found here,但它只適用於頁面。我如何獲得這個也適用於帖子?

add_filter('single_template', create_function('$t', 'foreach((array) get_the_category() as $cat) { if (file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php")) return TEMPLATEPATH . "/single-{$cat->term_id}.php"; } return $t;')); 

回答

0

根據您鏈接的網站,這應該適用於帖子和頁面。另外,根據WordPress文檔(http://codex.wordpress.org/Plugin_API/Filter_Reference/_single_template),'single_template'過濾器用於帖子和頁面。

你有一個單獨的single.php文件,名稱中包含正確的類別ID嗎?例如single-2.php

如果找不到正確命名的single.php文件,它將恢復爲標準的single.php文件。這是你所看到的嗎?

編輯:

如果您在WordPress管理區希望這個選項實際上,我建議使用郵政元來存儲您要使用的文件single.php中的價值。

你可以自定義元框添加到管理頁面http://codex.wordpress.org/Function_Reference/add_meta_box,那麼你可以使用一些代碼從你原來的問題來獲取所有可用的single.php模板文件,並把它們放到一個下拉列表:

$templates = array(); 
foreach((array) get_the_category() as $cat) { 
    if (file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php")) 
     $templates[] = TEMPLATEPATH . "/single-{$cat->term_id}.php"; 
} 

你會那麼需要類似的過濾器添加到您的原之一:

function custom_single_template($t){ 
    global $post; 

    if(get_post_meta($post->ID, 'name_of_key', true)) { 

     return TEMPLATEPATH . get_post_meta($post->ID, 'name_of_key', true); 

    } 

    return $t; 

} 
add_filter('single_template', 'custom_single_template'); 
+0

我上面的作品提供的代碼。問題是我想要一個下拉框,當我編輯/創建一個帖子時,要求使用哪個模板...就像我用這個函數創建一個頁面一樣。該插件具有此功能,但該功能沒有。 – siouxfan45

+0

啊,這不是你最初的問題。選擇頁面模板的功能是默認的Wordpress功能。我已經用一種方式更新了我的答案,您可以爲帖子做到這一點。 –

+0

對不起,我無法弄清楚這一點。感謝您的嘗試。 – siouxfan45

相關問題