add_filter('wp_title')不替换我的标题标签(WordPress插件)

Wou*_*den 7 wordpress plugins title

我正在尝试将我的详细信息页面的标题更改为汽车的名称.我制作了一个插件,用汽车信息填充详细页面.但现在我无法让add_filter('wp_title')在我的插件中运行.

这是我试过的代码:

function init() {
    hooks();
}
add_action('wp', 'init');

function hooks() {
    if(get_query_var('car_id') != "") {
        add_filter('wp_title', 'addTitle', 100);
        add_action('wp_head', 'fillHead');
    }
    add_shortcode('showCar', 'showCar');
}

function addTitle() {
    $api_url_klant = API_URL . '/gettitle/' . get_option("ac") . '/' . get_query_var('car_id');
    $title = getJSON($api_url_klant);
    return $title['merk'] . " " . $title['model'] . " - " . $title['bedrijf'];
}
Run Code Online (Sandbox Code Playgroud)

addTitle()函数工作得很好.它返回正确的名称.add_action('wp_head')也可以.我只是不能让wp_title过滤器无法工作.

我是在错误的时刻执行此过滤器还是我做错了什么?

Eri*_*rin 23

如果其他人遇到此问题,可能是由于Yoast插件.使用:

add_filter( 'pre_get_document_title', function( $title ){
    // Make any changes here
    return $title;
}, 999, 1 );
Run Code Online (Sandbox Code Playgroud)

  • 为了解决Yoast的标题过滤器,但保留`document_title_parts`的好处,我们也可以在`wpseo_title`过滤器中返回一个空字符串:`add_filter('wpseo_title','__ return_empty_string');`这似乎让Yoast回归到本机WordPress标题. (2认同)

Dan*_*l C 11

我无法从您提供的代码中看出来,但您使用的是:

<title><?php wp_title(); ?></title>
Run Code Online (Sandbox Code Playgroud)

在你的<head>,header.php下?

UPDATE

显然,从4.4开始处理标题的方式发生了变化.这是一个解释如何使用新代码的链接:

https://www.developersq.com/change-page-post-title-wordpress-4-4/

/*
 * Override default post/page title - example
 * @param array $title {
 *     The document title parts.
 *
 *     @type string $title   Title of the viewed page.
 *     @type string $page    Optional. Page number if paginated.
 *     @type string $tagline Optional. Site description when on home page.
 *     @type string $site    Optional. Site title when not on home page.
 * }
 *     @since WordPress 4.4
 *     @website: www.developersq.com
 *     @author: Aakash Dodiya
*/
add_filter('document_title_parts', 'dq_override_post_title', 10);
function dq_override_post_title($title){
   // change title for singular blog post
    if( is_singular( 'post' ) ){ 
        // change title parts here
        $title['title'] = 'EXAMPLE'; 
    $title['page'] = '2'; // optional
    $title['tagline'] = 'Home Of Genesis Themes'; // optional
        $title['site'] = 'DevelopersQ'; //optional
    }

    return $title; 
}
Run Code Online (Sandbox Code Playgroud)

  • 更新了我的答案以反映新的WordPress标题方法。 (2认同)