使用PHP在WordPress中设置页面标题

10 php wordpress

我知道这个问题之前已被问过几千次,但我尝试了很多这些解决方案而没有任何成功.

尝试过的解决方案等(添加到模板页面)

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' );
Run Code Online (Sandbox Code Playgroud)

方案是我有一个工作列表页面的自定义模板.这个页面有链接到位重写该重写domain.com/about/careers/search/job?slug=whateverdomain.com/about/careers/search/job/whatever-段塞被用于检索的Redis包含了所有的招聘启事,包括标题,我想使用信息的条目.

这是我如何重写URL(来自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);
Run Code Online (Sandbox Code Playgroud)

小智 8

我用我的模板做了一些研究。我的模板调用 get_header() 来打印带有 head 等的 HTML 标签,我猜你的也是如此。

为了替换标题,我在调用该函数之前开始输出缓冲,然后再获取它。

之后,我可以用 preg_replace() 轻松替换标题:

ob_start();
get_header();
$header = ob_get_clean();
$header = preg_replace('#<title>(.*?)<\/title>#', '<title>TEST</title>', $header);
echo $header;
Run Code Online (Sandbox Code Playgroud)