当你想要给一个建立在框架上的网站添加功能的时候,有时会很难决定是否要使用插件或子主题中的 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' );
当然,如果你想在其他位置输出列表的话,可以使用别的动作挂钩。
小结
插件是这个生态系统的另一部分,而这个生态系统就是你已创建的那部分框架。您可以创建一些插件,并专门设计成通过一些已添加到框架中的挂钩来激活,就像我上面所展示的那样。
在编写一个插件之前,值得花费一些时间去考虑并确定这样做正确与否。如有疑问,请参阅本文前面的信息图表来帮助你下定决心。