2014-02-28 #wordpress

Get Title Of Post Outside The Loop

For theme developers it is important that your theme page displays the correct page title. There can be some confusion in theme developer when they are working on a static page that is being used to display the a list of posts. By default your WordPress site will display a list of the most recent posts on the index.php page of your theme. But this will mean that it will be displayed on the home page of your website. If you want to have a different home page and then create a blog page to show the list of posts you need to change the posts page in the Settings -> Reading admin area.

The above allows me to assign the home page as the home page of the site, so I can use a different page template with a completely different layout to the blog page. I have also assigned the blog page which will display a list of the 10 most recent blog posts. Now that the blog posts page is not the home page of your theme I want to display the title at the top of the page. There are two ways of doing this you can allow the user to change the page template theme file, but the better option is to simply use the page title the user adds in the admin area. In WordPress you are provided with a function the_title() that will display the current title of global $post variable whatever that is set to at the current time.

<?php the_title(); ?>

This function works great when you are inside The Loop so you can use this function to display the title for all the blog posts. If you try to use the_title() function outside of the loop all you will return is the title of the first post and not the page title. To display the title of page outside of the loop then you can use an inbuilt WordPress function called single_post_title().

<?php single_post_title(); ?>

This will grab the page title and display this on the page. This function takes two parameters the first is a $prefix value, the second is if we return or echo the value. The follow code will prefix the page title with "Blog Page - " and will echo this straight out on the screen.

<?php single_post_title('Blog Page - ', TRUE); ?>

If you want to return this value then you just have to set the second parameter to FALSE.

$page_title = single_post_title('', FALSE); 


Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring