首页 > 解决方案 > 文件中没有循环的 Wordpress 标题,如 single.php

问题描述

嗨,我想了解使用 the_title() 之类的模板标签是否是循环外的良好行为。

我知道这类问题非常基本,但我找不到答案。

single.php - 循环内的 the_title:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>            
               <?php the_title(); ?>
          <?php endwhile; ?>
 <?php endif; ?>

single.php - 循环外的 the_title:

<?php the_title(); ?>

我从 underscores.me 下载了一个基本主题,如果我调查这些文件,我可以看到它们中的大多数都有一个循环(也像 page.php 或 single.php 这样的文件包含 get_template_part 其他包含循环的文件)。

当我按照一些教程进行操作时,我可以看到作者在循环外使用 the_title() 并且它可以工作,但是如果我阅读文档,我发现最好在内部使用它(我不是在谈论使用 echo get_the_title() 作为替代)。

我发现你也可以在循环外使用 single_post_title(),文档说它可以与单个帖子一起使用,我发现它适用于 page.php、single.php、home.php 等:

<?php single_post_title() ?>

有人可以给我正确的答案吗?

谢谢指教。

标签: wordpress

解决方案


您可以使用 echo get_the_title($post_id);


推荐阅读