0

Hello please i need a wordpress function.php code where i can choose how to display my title differently in section wp_title.

E.g.

If home, tag page, Category page, And Pages are viewed then "Normal Title".

But. And then post titles will have a conditional statement like.

If a post is under "Music" catgegory then the title will have a prefix "Download Music:" before the post title.

E.g Download Music: %post_title%

If a post under "Video" category then the title will have another prefix "Download Video:" before the post title.

E.g Download Video: %post_title%

Etc...

I hope i'm understood??.

0

You can add a filter in the title like:

add_filter('the_title', function ($title) {

if (is_single()) {
    $categories = get_the_category(get_the_ID());
    // Assuming the post has many categories will take the first
    $category = reset($categories);
    return $category->name .' - '.$title;
}
return $title;
});
| improve this answer | |
  • Please, This code doesnt work, but instead it adds The Prefix on Single page, and Nav bar menu not in <title> title. – Teejah James Jan 14 at 6:23
0

Document title renders in _wp_render_title_tag. If you want to modify it, you need to remove the WP function and create your own with similar logic.

Something similar to this:

remove_action('wp_head', '_wp_render_title_tag', 1);

And then:

add_filter('wp_head', function () {
    if (!current_theme_supports('title-tag')) {
        return;
    }

    if (did_action('wp_head') || doing_action('wp_head') && is_single()) {
        $categories = get_the_category();
        // Assuming the post has many categories will take the first
        $category = reset($categories);

        if ($category) {
            echo '<title>' . $category->name . ' - ' . get_the_title() . '</title>' . "\n";
        }
    }
    echo '<title>' . wp_get_document_title() . '</title>' . "\n";
});
| improve this answer | |

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.