为不同页面使用不同侧边栏文件

   WordPress 模板包含了 index.php(主页模板)、archive.php(Archive/Category模板)、404.php(Not Found 错误页模板)、page.php(内容页(Page)模板)、single.php(内容页(Post)模板)等主要文件。在这些文件中又引用了sidebar.php(侧栏模板)、header.php(Header模板)、footer.php(Footer模板)。

  很多博友为了在不同页面的侧边栏中显示不同的功能,在 sidebar.php 文件中利用 is_single() 等方法来判断当前页面的类型来改变显示的功能。这样做虽然没有问题,但过多的 php 操作会影响网页响影速度。查看 index.php 等文件,会发现引用 sidebar.php 文件的功能是用 WordPress 内置的 get_sidebar() 方法来完成的。该方法会在主题目录中查找 sidebar.php 文件,并将其包含进来。如果主题目录中没有 sidebar.php 文件,Wordpress 会将默认皮肤的 sidebar.php 文件包含进来(wp-content/themes/default/sidebar.php)。get_sidebar() 方法位于 wp-includes/general-template.php 文件中,内容如下:

  • function get_sidebar( $name = null ) {   
  •     do_action( ’get_sidebar’ );   
  •     $templates = array();   
  •     if ( isset($name) )   
  •         $templates[] = ”sidebar-{$name}.php”; // 根据 name 参数生成要包含的文件名   
  •     $templates[] = ”sidebar.php”;   
  •     if (” == locate_template($templates, true))   
  •         load_template( get_theme_root() . ’/default/sidebar.php’);   
  • }  
  • function get_sidebar( $name = null ) {
        do_action( 'get_sidebar' );
        $templates = array();
        if ( isset($name) )
            $templates[] = "sidebar-{$name}.php"; // 根据 name 参数生成要包含的文件名
        $templates[] = "sidebar.php";
        if ('' == locate_template($templates, true))
            load_template( get_theme_root() . '/default/sidebar.php');
    }

      get_sidebar() 方法有一个 name 的参数,该参数是可选的(大部分模板文件中没有指定这个参数),用来指定包含的文件名。例如希望 single.php 页面中包含自定义侧边栏文件 sidebar-single.php (必需保证该文件在模板目录下存在),可以加参数“single”:

  • get_sidebar(‘single’);  
  • get_sidebar('single');

      同一个页面文件中也可以多次调用这个方法,比如一个页面包含了左右两个侧边栏:

    view plain copy to clip board print ?

  • get_sidebar(‘left’);   
  • get_sidebar(‘right’);  
  • get_sidebar('left');
    get_sidebar('right');

      了解这个方法的用法,我们清理掉 sidebar.php 文件中过多的判断语句,为不同页面打造更加丰富多彩的侧边栏。

    来源:MXJAVA(mxjava.com)

    分享&收藏

    相关热文:

    1. 去掉wordpress博客侧栏功能版块中的wordpress.org
    2. WordPress主题模板制作及修改入门教程
    3. 五款wordpress广告插件 让博客成为赚钱利器
    4. 网络电话的深入比较分析
    5. Widget Logic–让你的WordPress在不同页面显示不同的侧边栏
    6. WordPress侧边栏错位的解决办法
    7. 传Facebook将与Skype进行广泛整合
    8. 全球奇人奇观 切勿模仿 一定不要模仿!!!!
    9. 宽带提速给网络电话带来的机遇
    10. 让WordPress友情链接只在首页显示
    11. 国际新锐PK国内巨头 网络电话选择技巧
    12. 国庆长假电话多 话费节省有“窍门”
    此条目发表在 科技 分类目录,贴了 , , 标签。将固定链接加入收藏夹。

    发表评论

    ͨ绰й绰 KC绰й绰

    ͨ绰й绰