WordPress 筆記

How Smart Tools Are Shaping the Future of Creative Work

Eric Chuang
2020-11-03

作為內容管理系統,WordPress 將網站的個區塊透過類似積木的方式模組化。以佈景主題來說,header.php 便掌管了 <body> 以前的 HTML 代碼、footer.php 則掌管 <footer>、</body> 到最後 </html> 的代碼。

我們在 WordPress 客製化中常見的勾點 wp_head 與 wp_footer 便是作用於這兩份檔案中。

頁面的主要內容,會先按照範本階級 (template hierarchy) 讀取頁面的範本檔,而在範本檔當中,我們便會看到 get_template_part() 這個函式。

基本語法

get_template_part( '路徑位置/檔名前綴', '代稱' );

// 從 WordPress 5.5 開始支援將參數傳遞至範本檔當中。
get_template_part( '路徑位置/檔名前綴', '代稱', array() );

以 WordPress 大部分的佈景主題為例,其 index.php 便會載入 get_template_part( 'template-parts/content', get_post_type() );。這段語法便會讀取 template-parts 資料夾中的 content-{{內容類型}}.php 檔案。

除了可以用來讀取主要內容的範本檔以外,也可以將頁面中的區段內容透過不同的範本檔儲存。以這次的公司網站改版為例,便將服務內容的區段儲存在 template-parts/section 中。

get_template_part() 的限制

根據 WordPress 的技術文件,get_template_part() 會執行 get_template_part 這個勾點,在意義上等同於 PHP 中的 require(),因此 get_template_part() 的值不能存為變數。

這一點會特別記下來,是因為之前曾經試圖用 get_template_part() 的內容插入 wp_nav_menu() 的 items_wrap 中,但沒有成功。

get_template_part() 對效能的影響

根據這篇文章的討論,get_template_part() 對效能並不會有太大的影響。雖然在執行上會增加讀寫的檔案數,但除非 template-parts 的範本檔案數量很多,且在頁面中大量使用 get_template_part() 來呼叫範本,不然對效能造成負面影響。

順手整理一下主要原因:get_template_part() 使用了 locate_template() 這個方法去偵測範本檔是否存在,而 locate_template() 使用了 foreach() 與 file_exists() 兩種方法,按照順位存取範本檔。

file_exists() 的結果會自動快取於 PHP 之中,所以即使重複使用,對效能的影響也不會太大。

foreach() 這個方法,雖然有可能會造成效能變慢,但在大多數的情況下並不會影響效能。

結語

這次的公司網站改版,為了將頁面寫死,不去存取區塊編輯器的內容,因此將每個頁面的內容藉由範本的方式儲存,也因而更了解 get_template_part() 的機制。

透過 get_template_part(),可以將不同的版面配置模組化,並且更有效率的在不同的情境下使用。

Sign up for our newsletter

Subscribe to our newsletter to receive the latest updates, expert insights, and practical tips directly in your inbox. Stay informed with content designed to help you grow.

+480.000 happy customers

Gain more with expert solutions

Unlock the full potential of your business with our expert solutions. Our team provides tailored strategies, professional guidance, and actionable insights to help you achieve better results.

  • Eric Chuang
  • •
  • 2025-01-23
如何同時使用 Webinoly 與 Cloudflare 保護網站安全

在社群夥伴勇哥的文章〈Webinoly 最新版快速安裝〉中,提到使用 Webinoly 來建立 WordPre […]

主機