【问题标题】:wp_title filter takes no effect on the <title> tagwp_title 过滤器对 <title> 标签无效
【发布时间】:2016-03-19 21:41:00
【问题描述】:

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

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函数中注入了title标签。

此外,如果我在标题中手动调用函数wp_title,它确实会返回预期值。

怎么了?我该如何解决?


补充:我的 WordPress 版本是 4.4。

【问题讨论】:

    标签: php html wordpress


    【解决方案1】:

    我终于发现WordPress核心代码变了,看下面这段代码。

    /**
     * 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 结果注入到标头 &lt;title&gt; 标记中,而是使用新函数 wp_get_document_title 做同样的事情。

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

    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/

    PS:查看函数 wp_get_document_title 的来源是个好主意,里面的钩子说明了很多。

    【讨论】:

    • 谢谢@fish_ball 完美的回答。
    • 终于!关于这个主题的所有其他帖子都是错误的 - 钉住它!谢谢!
    • 伙计...有时我讨厌 WordPress。为什么这么难找?
    • @JonathanGruber 成为贡献者,投我一票,你会再次爱上它的,哈哈!
    • @Adeel 我认为主题必须使用新功能add_theme_support( 'title-tag' )而不是旧功能wp_title
    【解决方案2】:

    不确定是否需要注入变量,但试试这个。

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

    【讨论】:

    • 谢谢,不过我自己终于找到了解决办法。
    • 太好了,不知道 :)
    【解决方案3】:

    您的head 标签中缺少title,添加&lt;head&gt; 标签

    &lt;title&gt;&lt;?php wp_title('|', true, 'left'); ?&gt;&lt;/title&gt; 你的 wp_filter 将正常工作。

    【讨论】:

    • 谢谢,不过我自己终于找到了解决办法。
    • 我们不需要这样做,因为核心函数wp_head()会做注入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2020-03-18
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多