How to set custom title of custom page template?
I try use wp_title
filter but it's not working.
Got success by adding this code to your-page-template.php
file before get_header()
function:
function my_page_title() {
return 'Your value is '; // add dynamic content to this title (if needed)
}
add_action( 'pre_get_document_title', 'my_page_title' );
function.php
file.
add_theme_support('title-tag')
in functions.php
Commented
Mar 8, 2021 at 10:45
You can do a conditional and check if you are on a custom post type page, and then update the title:
function my_wp_title( $title, $sep ) {
if (is_single('post-tyle')){
// Update the title here, for example : $title .= $title . $post->post_title;
}
return $title;
}
add_filter( 'wp_title', 'my_wp_title', 10, 2 );
However, your theme must support wp_title
. For doing so, add this in your theme's functions.php
file:
add_theme_support( 'title-tag' );
There are times when you cannot do this from functions.php (you don't have the data you want to output yet). For these cases:
make a new copied header file header-mycustom.php
and load it in your template
global $newtitle;
$newtitle="New Title";
get_header("mycustom");
in the header-mycustom.php
replace wp_head
with the following:
<?php
ob_start();
wp_head();
$output = ob_get_contents();
ob_end_clean();
global $newtitle;
$output=preg_replace("/<title>(.+)<\/title>/","<title>$newtitle</title>",$output);
echo $output;
?>
(This is the first time I feel I have to hack WP for such common task.)
wp_head
?