wp_title过滤器对< title>无效.标签 [英] wp_title filter takes no effect on the <title> tag

查看:97
本文介绍了wp_title过滤器对< title>无效.标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在主题functions.php文件中添加了以下过滤器:

I just added the following filter in my theme functions.php file:

function change_the_title() {
    return 'My modified title';
}
add_filter('wp_title', 'change_the_title');

在我的header.php中:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta id="viewport" name="viewport" content="width=device-width">
    <link rel="profile" href="http://gmpg.org/xfn/11">
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>">
    <?php wp_head(); ?>
</head>
<body <?php body_class();?>>

然后,我发现我的页面标题没有没有更改!然后将标题标签注入到wp_head函数中.

Then, I found the title of my page did NOT change! And the title tag was injected in the wp_head function.

更多,如果我在标题中手动调用函数wp_title,它将返回预期值.

More, if I call the function wp_title manually in the header, it does return the expected value.

怎么了?我该如何解决?

What's the matter? How can I work around it?

添加:我的WordPress版本是4.4.

Addition: My WordPress version is 4.4.

推荐答案

我终于发现WordPress核心代码已更改,请参见下面的代码.

I finally found out that the WordPress core code was changed, see the below piece of code.

/**
 * Displays title tag with content.
 *
 * @ignore
 * @since 4.1.0
 * @since 4.4.0 Improved title output replaced `wp_title()`.
 * @access private
 */
function _wp_render_title_tag() {
    if ( ! current_theme_supports( 'title-tag' ) ) {
        return;
    }

    echo '<title>' . wp_get_document_title() . '</title>' . "\n";
}

因此,在4.4之后,内核不会将wp_title结果注入到标头<title>标记中,而是使用新功能wp_get_document_title做同样的事情.

So, after 4.4, the core do not inject the wp_title result into the header <title> tag, but do the same thing with a new function wp_get_document_title.

因此,我们可以通过以下方式做同样的事情:

So instead, we can do the same thing by:

1.直接更改标题:

add_filter('pre_get_document_title', 'change_the_title');
function change_the_title() {
    return 'The expected title';
}

2.过滤标题部分:

add_filter('document_title_parts', 'filter_title_part');
function filter_title_part($title) {
    return array('a', 'b', 'c');
}

有关更多信息,请参见此处的详细信息: https://developer.wordpress.org/reference /functions/wp_get_document_title/

For more, see the details here: https://developer.wordpress.org/reference/functions/wp_get_document_title/

PS:研究函数wp_get_document_title的源是一个好主意,其中的钩子可以说明很多问题.

PS: Looking into the source of function wp_get_document_title is a good idea, the hooks inside which tells a lot.

这篇关于wp_title过滤器对&lt; title&gt;无效.标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆