gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:47:21 24 4
gpt4 key购买 nike

我知道这个问题已经被问过数千次了,但我已经尝试了很多这样的解决方案,但都没有成功。

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

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

场景是我有一个职位列表页面的自定义模板。此页面有 URL 重写,将 domain.com/about/careers/search/job?slug=whatever 重写为 domain.com/about/careers/search/job/whatever - slug 用于从 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);

最佳答案

我对我的模板做了一些研究。我的模板调用 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;

关于php - 使用 PHP 在 WordPress 中设置页面标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51309154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com