PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 5, 2022

[FIXED] Set page title in WordPress with PHP

 February 05, 2022     php, wordpress     No comments   

Issue

I know this question has been asked thousands of times before, but I have attempted a lot of these solutions without any success.

Attempted solutions, among others (added to the template page)

add_filter('the_title','callback_to_set_the_title');

add_filter('wp_title', 'callback_to_set_the_title');

global $title;
$title = 'My Custom Title';

add_filter( 'pre_get_document_title', 'callback_to_set_the_title' );

add_filter( 'document_title_parts', 'callback_to_set_the_title' );

The scenario is that I have a custom template for a job listing page. This page has URL rewriting in place that rewrites domain.com/about/careers/search/job?slug=whatever to domain.com/about/careers/search/job/whatever - the slug is used to retrieve an entry from Redis that contains all the information for the job listing including the title I'd like to use.

Here's how I am rewriting the URL (from functions.php):

function job_listing_url_rewrite() {
    global $wp_rewrite;
    add_rewrite_tag('%slug%', '([^&]+)');
    add_rewrite_rule('^about/careers/search/job/([a-zA-Z0-9-_]+)/?', 'index.php?page_id=6633&slug=$matches[1]', 'top');
    $wp_rewrite->flush_rules(true);
}
add_action('init', 'job_listing_url_rewrite', 10, 0);

Solution

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;


Answered By - Kapsonfire
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing