add_filter('wp_title') doesn't replace my title tag (WordPress plugin)

I am trying to change the title of my detail page to the name of the car. I have made a plugin that fills the detail page with the car information. But now I can't get the add_filter('wp_title') to work in my plugin.

Here is the code I tried:

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'];
}

The addTitle() function works just fine. It returns the right name. Also the add_action('wp_head') works as well. I only can't get the wp_title filter not to work.

Am I executing this filter at the wrong moment or what am I doing wrong?

Answers


I can't tell from the code you have provided, but are you using:

<title><?php wp_title(); ?></title>

in your <head>, under header.php?

UPDATE

Apparently a change was made to the way titles are handled as of 4.4. Here is a link that explains how to use the new code:

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; 
}

If anyone else is having problems with this, it may be due to the Yoast plugin. Use:

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

Need Your Help

QComboBox - set selected item based on the item's data

c++ qt user-interface combobox qcombobox

What would be the best way of selecting an item in a QT combo box out of a predefined list of enum based unique values.

Concatenate tuples using sum()

python sum tuples itertools

From this post I learned that you can concatenate tuples with: