0

I am trying to add custom text to title according to the tag selected.

For example:

If I've added a tag named 'Private', The title should look like "Page Title From title field + custom text assigned to the tag 'Private'".

i.e. "Iron Man - Review - Awesome"

here awesome will be the custom text assigned to the tag private.

Please help.

Thank you in advance.

2

The code below assumes that only one tag ( 'private' ) has a text associated with it:

function add_tag_text_to_title( $title, $id = null ) {
    if ( has_tag( 'private' ) ) { 
        return $title . ' - Awesome';
    } else {
        return $title;
    }
}
add_filter( 'the_title', 'add_tag_text_to_title', 10, 2 );

If you have more than one tag with text associated with it:

function add_tag_texts_to_title( $title, $id = null ) {
    $tag_texts = array (
        'tag1' => 'text1',
        'tag2' => 'text2',
        'tag3' => 'text3'
    );
    $new_title = $title;
    foreach ( $tag_texts as $key => $value ) {
        if ( has_tag( $key ) ) 
            $new_title .= ' - ' . $value;
    }
    return $new_title;
}
add_filter( 'the_title', 'add_tag_texts_to_title', 10, 2 );
|improve this answer|||||
  • Thank you, Frank. I'm very new to this and it would be great if you could tell me where I've to add this. – Jijo Jose Jun 21 '15 at 19:01
  • Add it to your theme's functions.php. – Frank P. Walentynowicz Jun 21 '15 at 19:06
  • The first one gave me error, so tried the second code. It worked. Thank alot. :) – Jijo Jose Jun 21 '15 at 19:15
  • I've edited the first example where in line 2 ')' was missing. Now it will work. – Frank P. Walentynowicz Jun 21 '15 at 19:18
  • Ran into a problem. Please check the titles of menu bar items here: shortofthemonth.com/film/jasmine – Jijo Jose Jun 21 '15 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.