Set page title in WordPress with PHP
I did some research with my template. My template calls get_header() to print the HTML tags with head and so on, and I guess yours does the same.
To replace the title, I start a output buffering right before calling that function and get it afterwards.
After that, I can replace the title easily with preg_replace():
ob_start();
get_header();
$header = ob_get_clean();
$header = preg_replace('#<title>(.*?)<\/title>#', '<title>TEST</title>', $header);
echo $header;
I understand that you have already tried using the wp_title
filter, but please try it the following way.
function job_listing_title_override ($title, $sep){
if (is_page_template('templates/job-listing.php')) {
$title = 'Job Listing Page '.$sep.' '. get_bloginfo( 'name', 'display' );
}
return $title;
}
add_filter( 'wp_title', 'job_listing_title_override', 10, 2 );
I suspect that the logic for altering wp_title in the template is firing too late.
In most cases, wp_title
is invoked in the header file, which will have been processed before getting to the template with your logic.
If you add the following to your functions.php
file, WordPress will set the title the way you intend.
<?php
// functions.php
function change_title_if_job_posting($query) {
$slug = $query->query->get('slug');
// The URL is a match, and your function above set the value of $slug on the query
if ('' !== $slug) {
/**
* Use the value of $slug here and reimplement whatever logic is
* currently in your template to get the data from Redis.
*
* For this example, we'll pretend it is set to var $data. :)
*/
$data = 'whatever-the-result-of-the-redis-req-and-subsequent-processing-is';
/**
* Changes the contents of the <title></title> tag.
*
* Break this out from a closure to it's own function
* if you want to also alter the get_the_title() function
* without duplicating logic!
*/
add_filter('wp_title', function($title) use ($data) {
return $data;
});
}
}
// This is the crux of it – we want to try hooking our function to the wp_title
// filter as soon as your `slug` variable is set to the WP_Query; not all the way down in the template.
add_action('parse_query', 'change_title_if_job_posting');
This will only add the function to the filter when the main WP_Query
has a variable set on it called "slug
", which should coincide with the logic you laid out above.