函数文档

the_title()

💡 云策文档标注

概述

the_title() 函数用于在 WordPress 循环中显示或检索当前文章的标题,支持添加前后标记。输出未转义,需注意安全风险。

关键要点

  • 函数必须在 The Loop 内使用,外部获取标题应使用 get_the_title()
  • 参数包括 $before(前置标记)、$after(后置标记)和 $display(控制输出或返回)
  • 输出未转义,可能包含 HTML 或 JavaScript,需防范跨站脚本攻击
  • 受保护或私密文章标题会自动添加“Protected: ”或“Private: ”前缀

代码示例

<?php the_title( '<h3>', '</h3>' ); ?>

注意事项

  • 避免允许不受信任用户创建文章标题,以防安全漏洞
  • 类似 the_content(),输出未转义,需在模板中适当处理

📄 原文内容

Displays or retrieves the current post title with optional markup.

Parameters

$beforestringoptional
Markup to prepend to the title. Default empty.
$afterstringoptional
Markup to append to the title. Default empty.
$displaybooloptional
Whether to echo or return the title. Default true for echo.

Default:true

Return

void|string Void if $display argument is true or the title is empty, current post title if $display is false.

More Information

This function displays or returns the unescaped title of the current post. This tag may only be used within The Loop, to get the title of a post outside of the loop use get_the_title. If the post is protected or private, this will be noted by the words “Protected: ” or “Private: ” prepended to the title.

Security considerations

Like the_content() , the output of the_title() is unescaped. This is considered a feature and not a bug, see the FAQ “Why are some users allowed to post unfiltered HTML?” . If the post title is alert("test");, then that JavaScript code will be run wherever the_title() is used. For this reason, do not write code that allows untrusted users to create post titles.

Source

function the_title( $before = '', $after = '', $display = true ) {
	$title = get_the_title();

	if ( strlen( $title ) === 0 ) {
		return;
	}

	$title = $before . $title . $after;

	if ( $display ) {
		echo $title;
	} else {
		return $title;
	}
}

Changelog

Version Description
0.71 Introduced.

User Contributed Notes