Sometimes we want to get current page title, which is displayed in
<title> tag. Here I mean the page in general meaning, not WordPress “page”. We have several WordPress functions that can help such as:
get_the_title(): to get current post/page/any post type title
single_cat_title(): to get current category title. There’re sibling functions for tags and terms as well:
get_bloginfo(): to get the blog name
Using those functions are great, but they have some disadvantages:
- Those functions are specific for particular pages like single post/page, category/tag, … pages. But we can have many page types in WordPress like: 404 page, search result page, archive page, or even virtual page.
- The title displayed differently in themes: you may use a theme that have title in format
Post Title | Blog Name, but another theme can use
Post Titleonly. You can make a combination of the functions above to achieve the correct title, but that won’t be used widely for other themes.
- Or you might set the title in various ways with SEO plugins
In this post, I’m gonna to use a simple trick that can solve these problems quickly.
I’m sure all of us are familiar with function
wp_title(), we often use this function in
header.php file, like this:
<title><?php wp_title( '|', true, 'right' ); ?></title>
to display the page title (you should use only this function to display page title, otherwise your site maybe not compatible with SEO plugins or causes performance issue).
The trick is switch the 2nd parameter
false to get the value of current page title:
$title = wp_title( '|', false, 'right' );
Here is an example where this technique is useful. We’re going to display a Twitter button. I’m gonna to use another cool technique to get the current page URL:
global $wp; $link = add_query_arg( $wp->query_string, '', home_url( $wp->request ) ); $text = wp_title( '|', false ); printf( '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="https://platform.twitter.com/widgets/tweet_button.html?url=%s&text=%s&count=horizontal"></iframe>', urlencode( $link ), rawurlencode( $text ) );
I’m currently use the script above (with some additions for Facebook like, Google+ buttons) for my websites. And it’s working great in archive pages where built in WordPress functions aren’t very helpful.