get_the_title()
Gets the title of the post for further use in php. You can specify the post whose title you want to get.
The function can be used inside a WordPress Loop without specifying a parameter, then the title of the current post will be returned. Or pass a post ID in the first parameter and the function will return the title of this specified post.
If the post is protected or private and you are on front-end, then "Protected" or "Private" will be displayed before the post title.
There is NO get_post_title() function in WordPress, use this function instead.
When you need to add post title to an HTML tag attribute, use the_title_attribute() function instead of the_title() or get_the_title().
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
Value of get_the_title() recommended to be cleaned before displaying because it displays all HTML tags as is, and it is not safe. There are two ways to clean it:
-
Full cleaning. Prevents the use of any HTML tags:
echo esc_html( get_the_title() );
- Partial cleaning. Allows you to leave the basic HTML tags (performance in this case suffers):
echo wp_kses_post( get_the_title() );
Hooks from the function
Return
String
. Post title.
Usage
get_the_title( $post );
- $post(int|WP_Post)
- Post ID or WP_Post object.
Default: global $post
Examples
#1 Print the current post title
echo get_the_title(); // or in H1 tag echo '<h1>'. esc_html( get_the_title() ) .'</h1>';
#2 Print the title of post 25
echo get_the_title( 25 ); // or pass parameter as object $the_post = get_post( 25 ); echo get_the_title( $the_post );
#3 Should the output be escaped with back slash
It depends on the context in which the function is used. As a rule, you don't need to escape it, WP does it itself. In particular, the following functions apply to the the_title hook:
Screening may be necessary when the header is rendered in a tag attribute:
<input type="text" value="<?= esc_attr( get_the_title() ) ?>">
Some general screening function can be put on the hook:
add_filter( 'the_title', 'my_escape_title' ); function my_escape_title( $title ){ return esc_html( $title ); }
Changelog
Since 0.71 | Introduced. |