2017-10-09 103 views
0

我有一個任務是創建一個特定於該類別的模板。所以我們說我有10個類別,但我想創建一個特定的模板讓我們說3個。所以如果類別是a,b或c,我會應用一個特定的模板。基於WordPress類別的模板

然後,當我創建一個帖子並將其附加到特定類別時,我需要顯示與該類別關聯的特定模板。

任何標題?

+0

@ali這可能有助於https://wordpress.org/plugins/custom-category-template/ – shashi

+0

謝謝@shashi我會檢查出來。 – mohsinali1317

+0

查看我對兩種不同解決方案的解答,這兩種解決方案都經過測試。 https://stackoverflow.com/a/46639563/4643292 – Dev

回答

0

高級自定義字段https://www.advancedcustomfields.com/插件應該允許您根據類別顯示不同的模板。它有一些漂亮的功能,但不記得它是否可以做到這一點。

有一個免費版本,所以試試看。讓我知道你如何去;)

0
  1. 刪除single.php中
  2. 一切插入「開關」代碼(見下文)
  3. 建立一個具有唯一名字3(三)新的模板。比如:single-a,single-b,single-c。
  4. 在服務器上,當被請求的頁面

請嘗試以下代碼同樣在修改single.php中神奇的仙塵會自動加載正確的模板。

if (in_category('21')) {include (TEMPLATEPATH . '/single-a.php'); 
} 
else if (in_category('22')) {include (TEMPLATEPATH . '/single-b.php'); 
} 
else if (in_category('23')) {include (TEMPLATEPATH . '/single-c.php'); 
} 
else { include (TEMPLATEPATH . '/single-29.php'); 
} 

對於不同的類別和您的主代碼,有單a,單b,單c是3個模板。

+0

在這裏,我們不討論關於後我們正在討論的類別所以根據我single.php一定不能過來這裏。它必須是category-a.php等等 –

+0

@Akshay Shah:請仔細閱讀問題。我的意思是這句話:「然後當我創建一個帖子並將其附加到特定類別時,我需要顯示與該類別相關的特定模板」 – javidrathod

+0

@Chaudhry Mohsin Ali:你試過這個嗎? – javidrathod

0

如果您參考Category_Templates

WordPress會自動檢索以下格式類別的文件:

category-slug.phpcategory-ID.php

比方說,你有3類,類別B類,類別c,要以不同的方式分配每個模板,您可以輕鬆創建category-a.php,category-b.php,category-c.php並將您的願望模板放入該文件中,而Wordpress將處理剩餘的內容。

0

在這裏,您可以用category_template

function wp_category_template($template) { 
    $cat = get_queried_object(); // get category object 
    if(1) // check condition 
     $template = locate_template('template.php'); // load template 
    return $template; 
} 
add_filter('category_template', 'wp_category_template'); 

或@shashi建議您可以使用插件custom-category-template

0

你有3種選擇:

選項1:您可以創建3個模板和按照WordPress Template Hierarchy這樣命名它們:

  • category-1.php
  • category-2。PHP
  • 類別的3.php

選項2:在功能使用的文件的PHP代碼加載3個不同類別1個模板:

add_filter('template_include', 'custom_category_template', 99); 

function custom_category_template($template) { 

    if (is_category(array(1,2,3) ) ) { 
     $new_template = locate_template(array('custom.php')); 
     if ('' != $new_template) { 
      return $new_template; 
     } 
    } 

    return $template; 
} 

使用in_category or is_category conditional tag這取決於你要爲特定類別的帖子加載模板,或者僅爲類別存檔頁面加載模板。

方案3:您可以選擇2與category_template filter使用代碼:

add_filter('category_template', 'custom_category_template'); 
function custom_category_template($template) { 

     if (is_category(array(1,2,3) ) ) { 

    $template = locate_template('custom.php'); 
    } 
    return $template; 
} 

假設你的類ID是1,2和3交換這些匹配您的安裝category i.d's