Get the Post/Page Title in WordPress using PHP

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.

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.

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.

echo get_the_title();

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.

// Display post title using post ID
echo get_the_title( 5 );
// Display post title and safely escape value
echo esc_html( get_the_title() );
// Using the_title function to automatically echo the title, while you can append or prepend the title using the function as displayed below
the_title( 'Before:', ' - After' )

I’ve also included an example of the_title() function which outputs the title without using echo. Typically I recommend using get_the_title() so you can modify the string if needed.

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!

Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 10 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way.

Leave a Reply

Your email address will not be published.

WordPress Tips Monthly

Get the latest from SmartWP to your inbox.