questions

Limit WooCommerce product title to a specific length (and add ‘…’)

Rate this post

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.

 

✔️Solution:

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.

Leave a Reply

Your email address will not be published.

Back to top button