the_title_attribute()
云策文档标注
概述
the_title_attribute() 函数用于在检索或显示时对当前标题进行清理,类似于 the_title(),但参数可以以字符串或数组形式提供。它会去除标签并应用 esc_attr() 以确保安全输出。
关键要点
- 函数作用:清理并输出或返回标题,适用于 HTML 属性(如 title 属性)。
- 参数 $args:可选,可以是字符串或数组,支持 before、after、echo 和 post 参数。
- 输出控制:通过 echo 参数决定是直接输出还是返回字符串。
- 安全处理:自动使用 strip_tags() 和 esc_attr() 进行清理。
代码示例
// 使用字符串参数
printf( '%s',
get_permalink(),
the_title_attribute( 'echo=0' ),
get_the_title()
);
// 使用数组参数
" title="<?php the_title_attribute( array(
'before' => 'Permalink to: ',
'after' => ''
) ); ?>">"
注意事项
- 如果标题为空字符串,函数将不输出任何内容。
- 默认情况下 echo 为 true,直接输出标题;设置为 false 可返回字符串供进一步处理。
- 相关函数包括 get_the_title()、esc_attr()、wp_parse_args() 和 get_post()。
原文内容
Sanitizes the current title when retrieving or displaying.
Description
Works like the_title() , except the parameters can be in a string or an array. See the function for what can be override in the $args parameter.
The title before it is displayed will have the tags stripped and esc_attr() before it is passed to the user or displayed. The default as with the_title() , is to display the title.
Parameters
$argsstring|arrayrequired-
Title attribute arguments. Optional.
beforestringMarkup to prepend to the title. Default empty.afterstringMarkup to append to the title. Default empty.echoboolWhether to echo or return the title. Default true for echo.postWP_PostCurrent post object to retrieve the title for.
Source
function the_title_attribute( $args = '' ) {
$defaults = array(
'before' => '',
'after' => '',
'echo' => true,
'post' => get_post(),
);
$parsed_args = wp_parse_args( $args, $defaults );
$title = get_the_title( $parsed_args['post'] );
if ( strlen( $title ) === 0 ) {
return;
}
$title = $parsed_args['before'] . $title . $parsed_args['after'];
$title = esc_attr( strip_tags( $title ) );
if ( $parsed_args['echo'] ) {
echo $title;
} else {
return $title;
}
}
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |
Skip to note 4 content
Codex
PHP with text args
printf( '<a href="%s" title="%s">%s</a>', get_permalink(), the_title_attribute( 'echo=0' ), get_the_title() );Skip to note 5 content
Codex
Inline with array args
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute( array( 'before' => 'Permalink to: ', 'after' => '' ) ); ?>"> </a>Skip to note 6 content
Codex
Inline with text args