skip to Main Content

I’m trying to limit the number of characters our WooCommerce product titles have, I found this PHP code:

add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
function shorten_woo_product_title( $title, $id ) {
    if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' ) {
        return substr( $title, 0, 30); // change last number to the number of characters you want
    } else {
        return $title;
    }
}

It works but I would like it to show the "…" at the end of each product title.

4

Answers


  1. You can use strlen() php function to target specific product title length to append to shortened title when product title is over a specific length:

    add_filter( 'the_title', 'shorten_woo_product_title', 10, 2 );
    function shorten_woo_product_title( $title, $id ) {
        if ( ! is_singular( array( 'product' ) ) && get_post_type( $id ) === 'product' && strlen( $title ) > 30 ) {
            return substr( $title, 0, 30) . '…'; // change last number to the number of characters you want
        } else {
            return $title;
        }
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    Login or Signup to reply.
  2. I use this code and change the character numbers to 40 but then it goes to 2nd line and then the alignment of add to cart button disturb, it get changed from other products alignmen .

    add_filter( ‘the_title’, ‘shorten_woo_product_title’, 10, 2 ); function shorten_woo_product_title( $title, $id ) { if ( ! is_singular( array( ‘product’ ) ) && get_post_type( $id ) === ‘product’ && strlen( $title ) > 30 ) { return substr( $title, 0, 30) . ‘…’; // change last number to the number of characters you want } else { return $title; } }

    Login or Signup to reply.
  3. You could do this with CSS by adding the following style attributes to the element containing the content you want to ellipsize. This would ensure that the content always displays to the edge of the element, without over-flowing.

    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    

    This method should be more performant than the JS solution and when implementing functionality like this, I’d always choose a pure-CSS solution if possible, before reverting to Javascript or trimming the string on the backend.

    Login or Signup to reply.
  4. white-space: nowrap;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
    overflow: hidden;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search