
內容簡介
Template Map 是一個實用外掛,旨在讓你更輕鬆地建立和管理自定主題中的導覽元素。它摒棄了在全局和頁首導覽系統中(如果你選擇不使用菜單)硬編碼文章 ID 等必須嵌入代碼的需求。
例如
很多時候,你也許會使用以下代碼來建立主網站導覽:
<nav>
<ul>
<li>
<a href="<?php echo get_permalink( 83 ); ?>">About</a>
</li>
</ul>
</nav>
這在最初開發期間很有效,且當你一次性地遷移至生產環境時仍然保持穩定。但是,當你正在進行後續更新時,開發環境中的文章 ID 與生產環境中的不同,這怎麼辦呢?你或許可以花時間每次同步資料庫,但這有點矯枉過正。這就是 Template Map 起作用的地方:
<nav>
<ul>
<li>
<?php $about_page_id = TemplateMap()->get_id_from_template( 'template-about.php' ); ?>
<a href="<?php echo get_permalink( $about_page_id ); ?>">About</a>
</li>
</ul>
</nav>
Template Map 允許你基於所指定的頁面模板動態地取得你想要的文章 ID。頁面模板檔名很少(或從來沒有)變更,因此這是 Template Map 實現的核心概念。一切都是由它開始運作的。
當然,這個方法假定你的頁面模板只使用一次,這點要記在心裡。現代客戶網站通常為每個網站部分的「父級」頁面使用唯一的頁面模板。
目前網站部分
Template Map 還可以更輕鬆地判定當前頁面是否位於網站「部分」內。其中,部分定義為具有任意子頁面和/或自訂文章類型的唯一頁面模板的頂層頁面。當你嘗試在導覽中設置「當前」狀態時,這非常有用,例如:
<nav>
<ul>
<li class="<?php if( TemplateMap()->maybe_in_section( 'template-about.php' ) ) : ?> current<?php endif; ?>">
<?php $about_page_id = TemplateMap()->get_id_from_template( 'template-about.php' ); ?>
<a href="<?php echo get_permalink( $about_page_id ); ?>">About</a>
</li>
</ul>
</nav>
基於同樣的原則,你可以使用此實用方法在當前頁面與網站「部分」之間條件地加載類別。
外掛標籤
開發者團隊
原文外掛簡介
Template Map is a utility plugin designed to make the creation and management of navigation elements in your custom theme that much easier. It abstracts the need to hard code post IDs and the like from your global and header navigation systems (if you choose to not use Menus) for instance.
For Example
Many times you may use something like the following to build your main site navigation:
That works great during initial development, and continues to hold up when you migrate to production en masse for the first time. But what about when you’re making subsequent updates and the post IDs in your development environment are different than those in production? You could take the time to sync the databases each and every time, but that’s a bit overkill. Here’s where Template Map comes in to play:
Template Map allows you to dynamically retreive your desired post ID based on the Page Template you told it to use. Page Template filenames rarely (if ever) change, so it’s the core concept of Template Map’s implementation. Everything works backwards from here.
Naturally this philosophy assumes your Page Template is used only once, it’s important to keep that in mind. Modern client sites often use unique Page Templates for the ‘parent’ pages of each site section.
Current Site Section
Template Map also makes it easier to determine whether the current page is within a site ‘section’ which is defined as a top level Page with a unique Page Template that has any number of child Pages and/or Custom Post Types within it. This is very useful when trying to set a ‘current’ state in your navigation, for example:
Based on the same principle you can use this utility method to properly orient yourself when outputting conditional classes contingent on the current page being within a ‘secton’ on your site.
