Include category title in wp_title

Create a helper function to get all parent categories (each post can be in multiple categories):

function parent_cat_names( $sep = '|' )
{
    if ( ! is_single() or array() === $categories = get_the_category() )
        return '';

    $parents = array ();

    foreach ( $categories as $category )
    {
        $parent = end( get_ancestors( $category->term_id, 'category' ) );

        if ( ! empty ( $parent ) )
            $top = get_category( $parent );
        else
            $top = $category;

        $parents[ $top->term_id ] = $top;
    }

    return esc_html( join( $sep, wp_list_pluck( $parents, 'name' ) ) );
}

Add the parent term with …

if ( '' !== $parent_cats = parent_cat_names( $sep ) )
    $title .= "$parent_cats $sep ";

Leave a Comment