I am trying to prepend a Woocommerce single product page title (in the header) with the category so it looks like
Category
Product Title
This is what I have so far:
function prepend_category_to_title($title, $id) {
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat = $term->name;
break;
}
if( is_product() ) {
$title = $product_cat . $title;
}
return $title;
}
add_filter('the_title', 'prepend_category_to_title', 10, 2);
I can get it to prepend the title fine but using the_title
outputs the category name to every single menu item and every single breadcrumb as well.
I see from this: https://wordpress.stackexchange.com/questions/309151/apply-the-title-filter-in-post-page-title-but-not-in-menu-title that this is expected behaviour and I can add further filters to remove these extra outputs. e.g. add_filter( 'pre_wp_nav_menu'...
But this seems horribly inefficient and messy. Additionally, prepending the title this way means that the category text also gets wrapped in the title <h1>
tags which I don't want as the category name needs to be above the product title in smaller <h5>
tags (and different font).
To make this slightly more complex, due to the theme I am using (Astra), the product title sits in a header outside of Woocommerce's
woocommerce_single_product_summary
hook.
How can I prepend the product title with the product category in a more elegant way? TIA!