Changing the Browser Tab Title for a Custom Post Type

I tried using the wp_title filter as described in another thread, but it’s not working for me. I know it is from 2017, so maybe things have changed?

add_filter( 'wp_title', [ $this, 'tab_title' ] );

public function tab_title( $page_title ) {
        return 'Test';

        // if ( is_singular( $this->post_type ) ) {
        //     $site_title = sanitize_text_field( get_option( 'mppi_site_title' ) );
        //     return trim( $page_title ) . ' | ' . $site_title;
        // }
        // return $page_title;
    } // End tab_title()

Hello @tkulow,

Thanks for writing to us.

I would suggest you please add this code to your active child theme .

    function custom_modify_document_title( $title_parts ) {
    // Remove the separator and site name if it's the front page or specific post types
    if ( is_front_page() || is_singular( 'your_custom_post_type' ) ) {
        // Just show the site name
        $title_parts['title'] = get_bloginfo( 'name' );
        unset( $title_parts['tagline'] ); // Optional: removes site tagline
    }

    return $title_parts;
}
add_filter( 'document_title_parts', 'custom_modify_document_title' );  

Please note that the code provided above or previous thread serves as a guide only and is to help you in getting started so implementing it and maintaining the code will be out of our support scope and for further maintenance for new possible versions of the theme that may cause the customization to break, you will need to hire a developer or subscribe to One where customization questions are answered.

Thanks

Thank you. That didn’t work, but found out that it because Yoast was installed and overriding it. I had to do:

add_filter( 'pre_get_document_title', [ $this, 'tab_title' ], 999999 );

public function tab_title( $title ) {
    if ( is_singular( $this->post_type ) ) {
        $site_title = sanitize_text_field( get_option( $this->post_type . '_site_title' ) );
        if ( !empty( $site_title ) ) {
            $page_title = preg_replace( '/\s*[-|]\s*.*$/', '', $title );
            return trim( $page_title ) . ' - ' . $site_title;
        }
    }
    return $title;
} // End tab_title()

You are most welcome, @tkulow