3.2    Index.php
以WordPress默认模板的index.php为例。我们先来看看它的结构:首先,通过<?php get_header(); ?>获得头信息;然后是一个循环体(The Loop,不知这样叫对不对);最后通过<?php get_sidebar(); ?>和<?php get_footer(); ?>加载侧边栏和页脚。

熟悉The Loop的用法能够让你随心所欲的控制文章的输出,因此我们来着重了解一下The Loop:

WordPress使用一个循环体来控制正文内容的显示,文章将按循环体内代码所定义的格式输出到当前页面上。部分模板标签必须在循环体内使用,如每篇文章的标题(the_title()),时间(the_time())和分类(the_category()) 。

简单表示如下:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
…找到相关内容则按格式输出正文…
<?php endwhile; else: ?>
…否则输出错误信息…
<?php endif; ?>

The Loop的用法非常灵活,比如你可以将其和分类标签结合起来以限定某个页面或某一部分只显示某个或几个分类的内容,这就是一个最简单的Asides。有兴 趣的自己不妨找找相关插件或模板来看看。我在这里仅举两个简单的例子。比如,如果你想要某一页面只显示分类x(x代表该分类的ID)的内容,你可以这样 写:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php if ( in_category('x') ) { ?>
…正文内容…
<?php } else { ?>
…其他内容…
<?php } ? >
<?php endwhile; else: ?>
…出错信息…
<?php endif; ?>

进一步,来看一个Asides的例子。假设你需要在某个页面的某一位置(比如侧边栏)输出某个分类的前x篇文章,你可以这样做:

<?php $temp_query = $wp_query; ?>
<?php query_posts('category_name=分类名字&showposts=x'); ?>
<?php while (have_posts()) : the_post(); ?>
…Asides内容…
<?php endwhile; ?>
<?php $wp_query = $temp_query; ?>

在这里,我们在Asides的循环体重使用变量temp_query来代替wp_query,以避免同正文部分的循环体发生冲突。更多的例子你可一在文后的参考文献中找到,代码大同小异。另外Durable的index.php也是一个不错的样板。

3.3    Sidebar.php
侧边栏的内容没有太多好说的,记住如果你想自己的侧边栏在不同页面显示不同内容,可以用3.1中提到的方法。我倾向于让用户使用Sidebar widgets或SBM(Sidebar Modules)来自行定义侧边栏的内容,这就是为什么Unnamed默认侧边栏内容偏少的原因。

在这里简单解释一下如何让主题支持Sidebar Widgets或SBM:
首先你需要建立一个functions.php,这个文件通常用于控制主题的后台内容,包括一些后台功能和管理页面。

然后在functions.php中加入下述代码:
if (function_exists('register_sidebar')) { register_sidebars(x,array('name'=>'Sidebar %d')); }

x代表sidebar的数量。

最后,修改Sidebar.php,以双侧边栏为例:


<div id="sidebar">
<div class="left-sidecolumn">
<ul>
<?php if ( function_exists('dynamic_sidebar') && dynamic_sidebar(1) ) : else : ?>
<li> … </li>
<?php endif; ?>
</ul>
</div>
<div class="right-sidecolumn">
<ul>
<?php if ( function_exists('dynamic_sidebar') && dynamic_sidebar(2) ) : else : ?>
<li> … </li>
<?php endif; ?>
</ul>
</div>
</div>

参考文献:

  1. The Loop
  2. Widgetizing Themes

相关文章

Tagged with:
 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Set your Twitter account name in your settings to use the TwitterBar Section.