0
votes

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!

1

1 Answers

0
votes

Yes it is based on hook so it will not create an issue. But if you need to proceed based on WooCommerce way then you need to skip WordPress hook the_title and need to use WooCommerce hook.

woocommerce_single_product_summary hook is associate with title, price, expert, .. on single product page. see below code of line that shows hook and there related function.

add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40 );
add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50 );

To go with Woocommerce, you need to remove the actual hook and reinitate the function like below. Hope below code justify your question.You can put this snippet in your theme's functions.php file

remove_action('woocommerce_single_product_summary','woocommerce_template_single_title',5);
add_action('woocommerce_single_product_summary', 'woocommerce_my_single_title',5);

if ( ! function_exists( 'woocommerce_my_single_title' ) ) {
   function woocommerce_my_single_title() {
?>
            /*
             your logic goes here
             No need to return data, just echo/print
            */
<?php
   }

}