當你想要給一個建立在框架上的網站新增功能的時候,有時會很難決定是否要使用外掛或子主題中的 functions.php 檔案。
在決定做什麼之前,我都會問自己幾個問題,如以下資訊圖表所示:

這將幫助你決定是否使用你的子或父主題函式檔案、外掛,或初始子主題。
如果您新增的功能增加了大量的程式碼,並能用於你開發的其他但非所有的網站上,那麼編寫一個外掛一般來說是最好的主意。
建立你的外掛
如果你決定需要一個外掛,那麼你可以利用之前新增到框架中的掛鉤,使它們變得更強大。例如:
如果你的外掛新增了瀏覽路徑記錄的功能,你可以將輸出鉤連到 wptp_above_content 行動掛鉤上,以顯示每一網頁內容上的瀏覽路徑。
如果你的外掛能建立一個更強大的或相關的搜尋框,你可以將它附加到 wptp_in_header 或 wptp_sidebar 行動掛鉤上。
一個建立呼叫動作框 (就像上節課中子主題中的函式) 的外掛,將附加到 wptp_sidebar 或 wptp_after_content 掛鉤上。
這樣的例子不勝列舉!
顯然,也有些外掛不會使用框架中的掛鉤,而會透過核心 WordPress 掛鉤啟用,但是你自己的掛鉤會帶給你更多的選擇。
例項——導航外掛
其中一個例項是導航外掛,我曾建立此外掛並運用到了我自己的框架之中。這個外掛僅能在當前頁面中被啟用,它首先會檢查當前頁面是否在層次結構中。如果當前頁面有子或父頁面,它就會顯示其層次結構中的頂層頁面和其子頁面的列表,讓你可以進行本地導航。
我在一些客戶網站上使用過這個外掛,運用其他的一些條件標籤將外掛附加到 before_content 掛鉤或 sidebar 掛鉤上,或同時附加到兩個掛鉤上。
該外掛使用了兩個函式:第一個是 wptp_check_for_page_tree(),用於找到頁面樹中的當前頁面:
-
function wptp_check_for_page_tree() {
-
-
//start by checking if we're on a page -
if( is_page() ) {
-
-
global $post;
-
-
// next check if the page has parents -
if ( $post->post_parent ) {
-
-
// fetch the list of ancestors -
$parents = array_reverse( get_post_ancestors( $post->ID ) );
-
-
// get the top level ancestor -
return $parents[0];
-
-
} -
-
// return the id - this will be the topmost ancestor if there is one, or the current page if not -
return $post->ID;
-
-
} -
-
}
接下來是 wptp_list_subpages(),用於檢查我們是否在某個頁面上 (而不是在主頁上),然後執行 wptp_check_for_page_tree() 函式,並根據其結果,輸出頁面列表:
-
function wptp_list_subpages() { -
-
// don't run on the main blog page
-
if ( is_page() && ! is_home() ) { -
-
// run the wptp_check_for_page_tree function to fetch top level page
-
$ancestor = wptp_check_for_page_tree();
-
-
// set the arguments for children of the ancestor page
-
$args = array(
-
'child_of' => $ancestor,
-
'depth' => '-1',
-
'title_li' => '',
-
);
-
-
// set a value for get_pages to check if it's empty
-
$list_pages = get_pages( $args );
-
-
// check if $list_pages has values
-
if ( $list_pages ) { -
-
// open a list with the ancestor page at the top
-
?>
-
<ul >
-
<?php // list ancestor page ?>
-
<li class="ancestor">
-
<a href="<?php echo get_permalink( $ancestor ); ?>"><?php echo get_the_title( $ancestor ); ?></a>
-
</li>
-
-
<?php -
// use wp_list_pages to list subpages of ancestor or current page -
wp_list_pages( $args );;
-
-
// close the page-tree list -
?> -
</ul>
-
-
<?php -
} -
} -
-
}
安裝並啟用外掛後,你需要在你的子主題中啟用它,新增以下內容到 functions.php 檔案:
-
add_action( 'wptp_sidebar', 'wptp_list_subpages' );
當然,如果你想在其他位置輸出列表的話,可以使用別的動作掛鉤。
小結
外掛是這個生態系統的另一部分,而這個生態系統就是你已建立的那部分框架。您可以建立一些外掛,並專門設計成透過一些已新增到框架中的掛鉤來啟用,就像我上面所展示的那樣。
在編寫一個外掛之前,值得花費一些時間去考慮並確定這樣做正確與否。如有疑問,請參閱本文前面的資訊圖表來幫助你下定決心。