wp_get_document_title()
Returns document title for the current page.
Hooks from the function
Return
String
. Tag with the document title.
Usage
wp_get_document_title();
Examples
#1 Demonstration of work
Let's say we are on the Contact page:
echo wp_get_document_title(); // outputs: Contacts - Site Name
#2 Page TITLE output
This is a replacement for template tag wp_title(). It is used in header.php to output header of any page.
This is a demo example, in WP this code is executed by function _wp_render_title_tag() which is hooked to wp_head hook. I.e. the code is executed in the HEAD part of HTML and to enable it, you need enable theme feature title-tag.
<head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width" /> <title><?php echo wp_get_document_title(); ?></title> <?php wp_head(); ?> </head>
#3 Let's output header title using the filter
Let's say we want this function to not work at all and through it we want to display our custom header, for example "My Page", on the page with ID 20:
// The title "My Page" will be displayed on page 20 add_filter( 'pre_get_document_title', function(){ global $post; if( $post->ID != 20 ){ return ''; // do not change anything } return 'My Page'; } );
#4 Redefining the function
You can write your own function and completely replace the work of this function. You can do it with pre_get_document_title hook:
add_filter( 'pre_get_document_title', 'my_get_document_title' ); function my_get_document_title(){ // Generate a dynamic header for each page. // You can take the code of this function as a basis and modify it to suit your needs. $title = 'This is a dynamically generated title'; return $title; }
#5 Change the separator between the header and the site name
By default, the function adds a ' - '
delimiter after the header site name. You can change the delimiter through a filter:
add_filter( 'document_title_separator', function(){ return ' | '; } );
#6 Remove the name of the site at the end of the header
To all titles on is_singular() pages, adds the site name, separated by a separator. This is not always good, let's fix it. To do this we use filter: document_title_parts:
// Remove the name of the site at the end of the header add_filter( 'document_title_parts', function( $parts ){ if( isset( $parts['site'] ) ){ unset( $parts['site'] ); } return $parts; } );
#7 Remove site description from the home page title
On the main page displays "Site name - site description". To remove the description and display only the title, use this hook:
// remove the description from the header for the home page add_filter( 'document_title_parts', function( $title ){ if( isset( $title['tagline'] ) ){ unset( $title['tagline'] ); } return $title; } );
Notes
- Global. Int. $page Page number of a single post.
- Global. Int. $paged Page number of a list of posts.
Changelog
Since 4.4.0 | Introduced. |