當你想要給一個建立在框架上的網站添加功能的時候,有時會很難決定是否要使用插件或子主題中的 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' );
當然,如果你想在其他位置輸出列表的話,可以使用別的動作掛鈎。
小結
插件是這個生態系統的另一部分,而這個生態系統就是你已創建的那部分框架。您可以創建一些插件,並專門設計成通過一些已添加到框架中的掛鈎來激活,就像我上面所展示的那樣。
在編寫一個插件之前,值得花費一些時間去考慮並確定這樣做正確與否。如有疑問,請參閲本文前面的信息圖表來幫助你下定決心。