WordPress at a glance

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.005307s = very slow | 50000 times = 2.55s = fast PHP 7.1.2, WP 4.7.3

No Hooks.

Return

String/null. String when echo is false.

Usage

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

Title attribute arguments. Optional.

  • $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.
    Default:

Default: ''

Examples

#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>

Code of the_title_attribute: wp-includes/post-template.php VER 4.9.8

<?php
function the_title_attribute( $args = '' ) {
	$defaults = array( 'before' => '', 'after' =>  '', 'echo' => true, 'post' => get_post() );
	$r = wp_parse_args( $args, $defaults );

	$title = get_the_title( $r['post'] );

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

	$title = $r['before'] . $title . $r['after'];
	$title = esc_attr( strip_tags( $title ) );

	if ( $r['echo'] ) {
		echo $title;
	} else {
		return $title;
	}
}

Related Functions

From tag: title (of post page)

More from category: Posts, pages...

More from Template Tags: Posts, Pages, ...

No comments
    Hello, !     Log In . Register