I don't have a good way to query a title string to fill in the content
You can use wp_get_document_title()
to get the document title.
So for example in your case: (see the docs for details on esc_attr()
)
<?php
// Put the title (string) in a variable.
$title_esc = esc_attr( wp_get_document_title() );
?>
<meta property='og:title' content='<?php echo $title_esc; ?>'/>
<meta property='twitter:title' content='<?php echo $title_esc; ?>'/>
I want to customize title format, like setting blog's name position
You can do that via the document_title_parts
hook.
But first, the document title has the following parts by default, and they're passed as an array to callbacks hooked to document_title_parts
:
| Part | Array key | Optional | Position |
|-------------------------------------|-----------|----------|----------|
| Title of the viewed page. | title | No | 1 |
| Page number if paginated. | page | Yes | 2 |
| Site description when on home page. | tagline | Yes | 3 |
| Site title when not on home page. | site | Yes | 4 |
The "optional" state means that the array item may or may not exist on certain pages — e.g. on page 1 of a category archive, the page
item doesn't exist (or is excluded) by default, but on page 2 and above, page
is included.
So for example, if you want the blog/site title to be the first instead of the default last:
function my_document_title_parts( $title ) {
if ( isset( $title['site'] ) ) {
$site = $title['site']; // get
unset( $title['site'] ); // unset
// Then put it at the top.
$title = array_merge( [ 'site' => $site ], $title );
}
// Remember to return an array.
return $title;
}
add_filter( 'document_title_parts', 'my_document_title_parts' );
And based on the above code, here are some sample output of var_dump( $title )
:
// Home page.
array (
'title' => 'My Site',
'tagline' => 'Just another cool WordPress site',
)
// Category page 2.
array (
'title' => 'Uncategorized',
'page' => 'Page 2',
'site' => 'My Site',
)
// Single Post.
array (
'title' => 'Markup: HTML Tags and Formatting',
'site' => 'My Site',
)
or using a different separator
You can do that via the document_title_separator
hook.
Here's an example for using |
than the default -
(i.e. a hypen):
function my_document_title_separator( $sep ) {
return '|';
}
add_filter( 'document_title_separator', 'my_document_title_separator' );
Notes
- Changing the title parts via
document_title_parts
or the title separator via document_title_separator
will also change the title parts/separator which WordPress use in the title
tag. There are solutions such as using a closure, but I'm not giving any examples for that (for now).
wp_get_document_title()
which you can use to get the document title, and for changing the title parts, seedocument_title_separator
anddocument_title_parts
.wp_get_document_title()
with the pattern' - '
right. Btw, could you post the answer so I could close the question please?-
/hypen), then you should use thedocument_title_separator
hook as in my answer.