讓WordPress不同的分類目錄的文章調用不同的模板

來源:互聯網
上載者:User

標籤:wordpress

近日,因為網站建設的需要,在沒有使用自訂文章類型的情況下,使用不同的分類目錄裡的文章調用不同的模板,作為註冊wordpress大學的見面禮。

首先在function.php裡,添加如下代碼:

//擷取並輸入某個分類的子分類

function post_is_in_descendant_category( $cats, $_post = null )

{

  foreach ( (array) $cats as $cat ) {

    // get_term_children() accepts integer ID only

    $descendants = get_term_children( (int) $cat, ‘category‘);

    if ( $descendants && in_category( $descendants, $_post ) )

      return true;

  }

  return false;

}


複製一份single.php,命名為:single-*.php檔案名稱(你可以根據自己的需要,製作多個 single-*.php 檔案,通過修改每個single-*.php 檔案的html結構和添加對應的CSS,就可以實現不同的文章頁面樣式 )。

將 single.php 裡面除了 get_header(); get_footer(); get_sidebar(); 之外的所有內容改成:

<?php

if ( in_category(‘16‘) || post_is_in_descendant_category(16) )//可自行修改 這裡包含分類目錄裡的文章和分類目錄裡的子分類目錄裡的文章

{

  include(TEMPLATEPATH .‘/single-16.php‘);

}

elseif ( in_category(‘7‘) || post_is_in_descendant_category(7) )//如果只有兩類single.php,可以不要這段,如果是多類,則添加多個elseif

{

  include(TEMPLATEPATH . ‘/single-7.php‘);

}

else{

  include(TEMPLATEPATH . ‘/single-other.php‘);

}//給其他分類的文章調用的。

?>

倡萌註:該文章的方法和倡萌之前分享的《WordPress不同分類使用不同的文章模板》的方法二一樣,就是使用 in_category() 函數來判斷,不同的地方就是添加了自訂函數 post_is_in_descendant_category() 來擷取某個分類的子分類。

如果有更多的技術技巧分享也請在www.diandian100.cn聯絡我,謝謝大家的分享

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.