How to get the title in WordPress template page
By Aj Khandal | Published: | 1 min read
Getting the title on a template page is a very common requirement when creating templates in WordPress. There are two main functions you can use:
get_the_title()
the_title()
get_the_title()
get_the_title( int|WP_Post $post )
You can pass a post ID in the parentheses to get a specific post's title. By default, it uses the current $post.
the_title()
the_title( string $before = '', string $after = '', bool $echo = true )
Displays or retrieves the current post title with optional markup.
Parameters
$before (string, optional)
- Markup to prepend to the title. Default:
''.
$after (string, optional)
- Markup to append to the title. Default:
''.
$echo (bool, optional)
- Whether to echo or return the title. Default:
true (echo).
Examples
<?php echo get_the_title( $post_id ); ?>
<?php the_title(); ?>
Difference between the_title() and echo get_the_title()
The two are not 100% identical, though they are close and give the same results in most cases.
the_title() will echo the title by default, but the third parameter ($echo) can be used to change that behavior.
the_title() prepends the optional $before and appends the optional $after arguments to the output.