试图在声明周围回应H2标签

时间:2014-08-04 15:24:13

标签: php html wordpress

我想要一个包含在h2标签中的标题声明。我期待这很简单,但它在标题之后回应了h2标签。它以下列方式显示:

我使用的代码:

echo "<h2>".the_title()."</h2>";

结果:

title
<h2></h2>

如何更正此行为并确保回显的标题在h2标记之间结束?

4 个答案:

答案 0 :(得分:7)

我讨厌WordPress。您有几个选项http://codex.wordpress.org/Function_Reference/the_title

the_title('<h2>', '</h2>', true);

或者:

echo "<h2>" . the_title(null, null, false) . "</h2>";

http://codex.wordpress.org/Function_Reference/get_the_title

echo "<h2>" . get_the_title() . "</h2>";

答案 1 :(得分:3)

如果你只是写:

the_title();

输出标题 - 即使没有echo!这是因为输出它是the_title的副作用。在我看来,这是一个糟糕的编程设计,但这就是他们选择这样做的方式。

所以当你写:

echo "<h2>".the_title()."</h2>";

PHP正在进行中:

  • 处理表达式:
    • "<h2>"
    • 与...结合。
    • the_title()的返回值
      • 致电the_title() - 这会输出标题!
      • 返回值:null
      • null投射到字符串:""
    • 与...结合。
    • "</h2>"
  • 结果:title goes here<h2></h2>

您可以尝试:

echo "<h2>"; the_title(); echo "</h2>";

但是我很确定有一个函数只返回标题而不是输出它,只需检查文档。

答案 2 :(得分:2)

the_title功能改为return一个字符串,而不是echoprint

或者,分别输出三个字符串。

<h2><?php the_title(); ?></h2>

答案 3 :(得分:0)

这对我来说似乎是最干净的

<?php the_title('<h1>');?>