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.

1 Answer 1

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 );
6
  • 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
    Commented Jun 21, 2015 at 19:01
  • Add it to your theme's functions.php. Commented Jun 21, 2015 at 19:06
  • The first one gave me error, so tried the second code. It worked. Thank alot. :)
    – Jijo Jose
    Commented Jun 21, 2015 at 19:15
  • I've edited the first example where in line 2 ')' was missing. Now it will work. Commented Jun 21, 2015 at 19:18
  • Ran into a problem. Please check the titles of menu bar items here: shortofthemonth.com/film/jasmine
    – Jijo Jose
    Commented Jun 21, 2015 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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