custom field to always to .get_the_title()?

Is there a way to have always the the_title() tag also includes a custom field called subtitle?

I want to have a title like this: “subtitle-custom-field: Post Title“. For example, “Cool: The new TV show from Werner Herzog.”

In this case, cool would be the custom field value, and the new TV… would be the_title().

I am getting this at the moment with the following code:

<h1><?php $values = get_post_custom_values("myCustomField"); echo $values[0]; ?>: <?php the_title(); ?>"><?php $values = get_post_custom_values("myCustomField"); echo $values[0]; ?>

<p><?php the_title(); ?></p></h1>

The Problem is, that Google indexes the posts sometimes with the custom field in title, sometimes without it – which in some cases makes no sense. I also gave all possible “title tags” the complete title the same way in the title= attribute.

Is there any way to tell WordPress if there’s a custom field subtext, print it always in front of the post_title?

2 Answers
2

<?php
function add_subtitle($title, $id) {
    $subtitle = get_post_meta($id, 'myCustomField', true);
    $new_title = $title;
    if(!empty($subtitle))
        $new_title = $subtitle . ': ' . $new_title;
    return $new_title;
}
add_filter('the_title', 'add_subtitle', 10, 2);

Basically, this uses the the_title filter to add the subtitle to your title. It only adds it if that custom field is available, otherwise, it leaves the title alone.

Leave a Comment