sourskittle
sourskittle

Reputation: 21

How to truncate characters in product description with WooCommerce

I have found out how to add a short description to the thumbnails for products in WooCommerce, but how do I truncate them to a certain length, say 30 characters. All the answers to do with editing the functions.php file dont mention where in the file to put the code.

My code in my functions.php file is:

add_action('woocommerce_after_shop_loop_item_title','add_title_description',9);
function add_title_description(){
  echo get_post_meta($product->id, 'title-description', true)? '<span class="title-description">' . get_post_meta($product->id, 'title-description', true) . '</span><br />' : '';
}

Upvotes: 2

Views: 1884

Answers (3)

Shawn W
Shawn W

Reputation: 566

My implementation grabbing the first 2 sentences instead of a character count.

/**
* Echo Truncated String
*
* @param  string $string
* @return string
*/

function add_title_description( $titleDescription ) {
global $product;

    $titleDescription = get_post_meta( $product->id, 'title-description', true );
    
    // combine first 2 sentences
    $sentence = preg_split( '/(\.|!|\?)\s/', $titleDescription, 3, PREG_SPLIT_DELIM_CAPTURE );
    
    echo $titleDescription ? '<span class="title-description">' . $sentence[0] . $sentence[3] . '</span><br />' : '';

}


add_action( 'woocommerce_after_shop_loop_item_title', 'add_title_description', 4, 1 );

Upvotes: 1

alemarengo
alemarengo

Reputation: 91

I added this:

    function wcs_excerpt_length( $length ) {
     return 15;
}
add_filter( 'product_description_length', 'wcs_excerpt_length' );

Upvotes: 0

Simone Nigro
Simone Nigro

Reputation: 4887

use substr()

add_action('woocommerce_after_shop_loop_item_title','add_title_description',9);

function add_title_description()
{
    $titleDescription = get_post_meta($product->id, 'title-description', true);

    if( !empty($titleDescription) )
    {
        if( strlen($titleDescription) > 30 )
            $titleDescription = substr($titleDescription, 30);

            printf('<span class="title-description">%s</span><br />', $titleDescription);
        }
}

Upvotes: 2

Related Questions