If you are developing custom WordPress functionality one important element is a post or page’s title. Luckily WordPress has a built in function to retrieve the title of the current post using PHP. This is useful for displaying a post title in a custom loop or in other areas of your WordPress site’s theme.
In this article I’ll be going over how to use the get_the_title() function in WordPress.
How to Display the Page/Post Title in PHP
Now let’s dive in and use get_the_title() to display our page/post’s title in WordPress using PHP. This is useful if you’re creating a custom theme or custom code snippet. Best of all the function will output the title of any post type including pages and posts. If you add custom post types to your site it’ll also work for retrieving their title as well.
You can easily echo the get_the_title function and it’ll output the current global $post object’s title. This will work in most use cases and likely what you need.
Alternatively you can set the post ID in the get_the_title function to get a specific post’s title. You can see in the examples below how I am getting a post/page’s title by ID. This works great too if you have a custom loop you’ve created and want to grab the title that way.
I’ve also included an example of the_title() function which outputs the title without using echo. the_title() function also allows you to include content before and after the title as seen in the example above. Typically I recommend using get_the_title() so you can modify the title string if needed.
If you use get_the_title() function on a password protected or private post the words “Protected” and “Private” will be inserted before the post title.
If you’re using the title as a title tag in an HTML tag you can also use the function the_title_attribute() which will echo a sanitized version of the title. This will prevent things like quotation marks from breaking your layout when using a title in an HTML attribute.
I hope this post cleared up how to get the page title in WordPress using PHP.
If you have any questions about WordPress development let me know in the comments below!