1

How to set custom title of custom page template?

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

  • Are you using the filter before calling the wp_head? – Bruno Cantuaria Jun 12 '17 at 14:32
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' );
| improve this answer | |
0

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' );
| improve this answer | |
  • This should be added in the themes function.php file. – Howdy_McGee Nov 27 '18 at 4:08
  • hope this worked from the template file but doesn't – Fanky May 22 '19 at 15:47
0

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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