Replace category titles

I want to display different titles in category archives than the category title.

I have created a function with if statements for this purpose:

function category_titles_change() {
    if (is_category('name1')) { ?  
        new title 1
    ?php }
    elseif (is_category('name2')) { ?  
        new title 2
    ?php }
    elseif (is_category('name3')) { ?  
        new title 3
    ?php }
}

How can I use this to change the title/title shown in the head/head

I have tried this:

function head_category_titles_change() {    
 if (is_category()) { ? 
 title 
?php category_titles_change(); ? 
 /title 
?php }}
add_action( 'wp_head', 'head_category_titles_change' );

But this ads a second title to the head in addition to the default title. How can I replace the default Title in Category archives with my desired titles?

Topic wp-title wp-head filters categories hooks Wordpress

Category Web


You shouldn't use wp_head action - it doesn't give you a chance to modify title that is already printed. But WordPress has special hook for that: wp_title.

The code below should do the trick:

function my_change_category_title( $title, $sep ) {
    if ( is_category('name1') ) {
        return 'Cat 1 title';
    }
    if ( is_category('name2') ) {
        return 'Cat 2 title';
    }
    ...

    return $title;
}
add_filter( 'wp_title', 'my_change_category_title', 10, 2 );

You can also try to use pre_get_document_title hook with the same filter function.


Well thank you for this question i did this after you posted this

function category_title( $title ){
if( is_category('name1') ){
    $title = 'name1 title';
}elseif( is_category('name2') ){
    $title = 'name2 title';
}
return $title;
}
add_filter( 'get_the_archive_title', 'category_title' );

Hope this helps

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.