1

How to set custom title of custom page template?

I try use wp_title filter but it's not working.

1
  • Are you using the filter before calling the wp_head? Commented Jun 12, 2017 at 14:32

3 Answers 3

2

Reference

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' );
3
  • This should be added in the themes function.php file.
    – Howdy_McGee
    Commented Nov 27, 2018 at 4:08
  • hope this worked from the template file but doesn't
    – Fanky
    Commented May 22, 2019 at 15:47
  • Your theme must add_theme_support('title-tag') in functions.php
    – ericek111
    Commented Mar 8, 2021 at 10:45
0

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' );
-1

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.)

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.