the_title_attribute()WP 2.3.0

Displays the title of the post prepared (sanitized) for use in the HTML attributes of HTML tag.

The function should be used inside a WordPress Loop.

Works like the_title(), except the parameters can be in a string or an array. See the function for what can be overridden in the $args parameter.

The function is identical to the_title(), the only difference is that this function "cleans" the title from HTML tags and sanitize HTML entities (<, >, ", '). For example, symbol < will be replaced by &lt;. Before the output it pass the post title through functions: esc_attr() and strip_tags().

1 time — 0.005307 sec (very slow) | 50000 times — 2.55 sec (fast) | PHP 7.1.2, WP 4.7.3

No Hooks.

Return

null|String. Void if 'echo' argument is true, the title attribute if 'echo' is false.

Usage

the_title_attribute( $args );
$args(string|array)

Title attribute arguments. Optional.

Default: ''

  • before(string)
    Markup to prepend to the title.
    Default: ''

  • after(string)
    Markup to append to the title.
    Default: ''

  • echo(true|false)
    Whether to echo or return the title.
    Default: true for echo

  • post(WP_Post)
    Current post object to retrieve the title for.

Examples

0

#1 An example of using the function in the title attribute of the <a> tag.

Since this attribute does not allow to use HTML tags, quotes, and other things, we can't use the_title() function, but the_title_attribute() suit perfectly here:

<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute([ 'before'=>'Permalink to: ' ]); ?>">
	<?php the_title(); ?>
</a>

Changelog

Since 2.3.0 Introduced.

the_title_attribute() code WP 6.5.2

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;
	}
}