Search code examples
phpwordpresswoocommercehook-woocommerce

Trim Related Products Title Length - Woocommerce


I currently have an issue with trimming the length of the product title in the "Related Products" section of my single product page.

I have set up a custom hook pointing to a custom template for this. The only problem is that it isn't trimming any of it - it is still printing the whole title.

I have tried to use get_the_title() and it doesn't print anything to screen, so in the code below I have tried to pass the title as a string and not an array.

What am I doing wrong?

<?php $title = the_title('<h3 class="product_title entry-title">', '</h3>'); 

    $text = wp_trim_words($title, 2, '...')

?>
<?php echo $text; ?>

Thanks in advance Regards Michael


Solution

  • the_title() will be auto print as you don't need to echo it.

    You need to use filter for title as the following in functions.php,

    function trim_title( $title ) {
    
      $title = wp_trim_words( $title , 40, '...' );
    
      return $title;
    }
    add_filter( 'the_title', 'trim_title', 10, 1 );