wordpress主题制作教程(十):制作文章单页模板single.php

在前一篇教程中我们已经只做好了index.php,这个文件可以当首页使用,也可以当分类、标签等归档页使用,这篇教程我们来制作一下文章的具体页面-文章单页模板,如果我们没有但页模板single.php,那么就会使用index.php文件来代替,不过对于文章单页,我们还需要添加一些其他的信息,比如版权申明、相关文章、评论等等,所以我们应该另外制作一个模板,在我们下载的主题文件夹下面已经有了single.php文件。你可以试着删除这个文件,然后再去看看用index.php显示文章的效果。

用编辑器打开主题文件夹下面的single.php文件,在前面的教程中我们已经将这个文件中的头部、底部、侧边栏代码替换成了加载对应模板的代码。对于文章单页,我们的文章框架代码页需要放在一个循环中,只不过到了单页面,只循环一次。所以你完全可以将index.php里面的代码全部复制过来,再添加,修改。

一、文章标题
找到文章标题:

  1. <h3 class="title"><a href="single.html">Loreum ipsium massa cras phasellus</a></h3>  

还记得我们上篇教程讲的获取文章链接、标题的代码吗?

  1. <h3 class="title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>  

二、文章标签:

  1. <a href="#">News</a>, <a href="#">Products</a>  

改成

  1. <?php the_tags('标签:', ', ', ''); ?>  

三、日期
将日期改为:

  1. <?php the_time('Y年n月j日') ?>  

四、评论数

  1. <a href="#">7 Comments</a>  

改成

  1. <?php comments_popup_link('0 条评论', '1 条评论', '% 条评论', '', '评论已关闭'); ?>  

五、文章内容。
先将文章的图片删了,删除下面的代码:

  1. <img class="thumb" src="<?php bloginfo('template_url'); ?>/images/610x150.gif" alt=""/>  

然后将所有文章内容,即:之间的代码全部删除,替换成:

  1. <?php the_content(); ?>  

六、评论和返回首页

  1. <p class="clearfix"> <a href="blog.html" class="button float" >&lt;&lt; Back to Blog</a> <a href="#commentform" class="button float right" >Discuss this post</a> </p>  

改成:

  1. <p class="clearfix"> <a href="<?php echo get_option('home'); ?>" class="button float" >&lt;&lt; 返回首页</a> <a href="#commentform" class="button float right" >发表评论</a> </p>  

好了,前面说过文章单页的内容页需要放在一个循环语句中(事实上是我们需要在输出文章的前面执行the_post()函数,这个函数会生成文章变量$post)。
的后面添加代码,效果:

  1. <!-- Column 1 /Content -->   
  2.     <?php if (have_posts()) : the_post(); update_post_caches($posts); ?>  

然后在代码

  1. </div>   
  2.     <?php get_sidebar(); ?>  

的前面,注意咯。“的前面”添加代码,完成效果:

  1. </div>   
  2.    <?php else : ?>   
  3.    <div class="errorbox">   
  4.        没有文章!   
  5.    </div>   
  6.    <?php endif; ?>   
  7.    <?php get_sidebar(); ?>  

这里的操作跟首页差不多,不过这里只需要输出一篇文章,所以while添加与否没有多大关系,需要提醒的是,一定要记住添加了if,就得有endif,添加了while,就得有endwhile。
可能其他语法不会这样用,其实这里你也可以改成用{}的。比如:

  1. <?php if( have_posts() ){ the_post();?>   
  2. <!--文章代码-->   
  3. <?php } ?>  

OK,文章单页制作方法就完成了。

已有3条评论

xuexi进行回复 取消回复