Limits Product Titles Lenght

Limits the display length of product titles in WooCommerce.

PHP
/**
 * Snippet Name:     Limits product titles lenght
 * Snippet Author:   coding-bunny.com
 * Description:      Limits the display length of product titles in WooCommerce.
 */

function cb_limit_product_title_length( $title, $id ) {
    // Check if we are on the shop or archive pages, or if the product is in a related loop
    if ( ( is_shop() || is_archive() || ( isset( $GLOBALS['woocommerce_loop']['name'] ) && $GLOBALS['woocommerce_loop']['name'] === 'related' ) ) 
          && 'product' === get_post_type( $id ) ) ) {
        
        $max_length = 60; // Maximum number of characters to display

        // Abbreviate the title if it exceeds the maximum length
        if ( mb_strlen( $title ) > $max_length ) {
            return mb_substr( $title, 0, $max_length ) . '...';
        }
    }
    return $title; // Return the original title if conditions are not met
}

add_filter( 'the_title', 'cb_limit_product_title_length', 10, 2 );

How To Implement This Solution?

Leave a Reply