构建HTML正文

接下来我们学习如何在正文中添加基本HTML标签:
1、打开index.php文件,在 body 标签内加入以下代码:

<header>
	<h1><?php bloginfo('name'); ?></h1>
</header>

保存,返回浏览器刷新,我们看到页面出现了标题“从0到1制作WordPress主题”,差不多你已经明白了 bloginfo(‘name’) 函数可以动态的把title内容插入标签

2、如果我们想要更改前端输出,我们可以转到“设置”,并将“站点标题”更改为其他名字,例如“Simple主题制作”,

保存更改,返回前端页面刷新就可以看到效果。
3、除了大标题,我们还可以加入标语。 用small标签配合bloginfo(),但不使用name参数,我们使用 description 参数,如下面的代码块所示:

<header>
	<h1><?php bloginfo('name'); ?></h1>
	<small><?php bloginfo('description'); ?></small>
</header>

保存代码,返回浏览器刷新前端页面,看到之前设置的站点副标题出现在页面上

4、接下来我们输入更多代码,如下:

<div class="main">
	<?php if(have_posts()) : ?> 
		post found
	<?php else : ?>
		<?php echo wpautop('Sorry, No posts were found'); ?>
	<?php endif; ?> 
</div>

我们在header标签下输入了class为main的div代码块,WordPress使用称为循环或主循环的东西来获取我们的每篇博客帖子,无论类别或其他任何类型。if(have_posts()) 查看是否有帖子,有帖子就返回 post found ,没有帖子就进入php else : 部分,输出 Sorry, No posts were found;endif 用来结束 if 语句。**echo wpautop()**的作用是它会双线换行并自动将输出内容变成段落。

5、保存代码,返回浏览器刷新页面,可以看到post found,返回网站后台进入“文章”选项,发现有一篇《你好,世界》的文章,点击“编辑”来修改文章,把标题改成《从0到1制作WordPress主题》,然后点击更新。

6、回到index.php文件,将 post found 替换为以下代码:

<?php while(have_posts()): the_post(); ?>
	<h3><?php the_title(); ?></h3>
	<div class="meta">
	Created By <?php the_author(); ?> on <?php the_date('l jS \of F Y h:i:s A'); ?>
	</div>
	<?php the_content(); ?>
<?php endwhile; ?>

保存,返回前端刷新页面,

刚才发生了什么?

  • if(have_posts()) – 检查博客是否有日志。
  • while(have_posts()) – 如果有日志,那么当博客有日志的时候,执行下面 the_post() 这个函数。
  • the_post() – 调用具体的日志来显示。
  • the_title() –调用日志标题
  • the_author() –它是输出当前日志作者的名字
  • the_date(‘l jS \of F Y h:i:s A’) – 调用日志发布日期,并以固定格式显示
  • the_content() 函数调用了 日志的内容
  • endwhile; – 遵照规则 #1,这里用于关闭 while()
  • endif; – 关闭 if()

7、接下来我们加入footer 标签,让站点动态显示版权信息,在body 的结束标签上方输入以下代码:

<footer>
	<p>© <?php the_date('Y'); ?>-<?php bloginfo('name'); ?></p>
</footer>

回到前端刷新,我们看到了 © 2018-从0到1制作WordPress主题。

现在来回顾以下本节添加的所有代码

<header>
	<h1><?php bloginfo('name'); ?></h1>
	<small><?php bloginfo('description'); ?></small>
</header>

<div class="main">
	<?php if(have_posts()) : ?> 
        <?php while(have_posts()): the_post(); ?>
	        <h3><?php the_title(); ?></h3>
	        <div class="meta">
	        Created By <?php the_author(); ?> on <?php the_date('l jS \of F Y h:i:s A'); ?>
	        </div>
	        <?php the_content(); ?>
        <?php endwhile; ?>
	<?php else : ?>
		<?php echo wpautop('Sorry, No posts were found'); ?>
	<?php endif; ?> 
</div>

<footer>
	<p>© <?php the_date('Y'); ?>-<?php bloginfo('name'); ?></p>
</footer>