primaltwins
primaltwins

Reputation: 77

Woocommerce product description length characters

I added the following code to my functions.php file to add a short product description under the thumbnails on my shop page.

add_action( 'woocommerce_after_shop_loop_item_title', 'lk_woocommerce_product_excerpt', 35, 2);
if (!function_exists('lk_woocommerce_product_excerpt'))
{
function lk_woocommerce_product_excerpt()
{
$content_length = 20;
global $post;
$content = $post->post_excerpt;
$wordarray = explode(' ', $content, $content_length + 1);
if(count($wordarray) > $content_length) :
array_pop($wordarray);
array_push($wordarray, '...');
$content = implode(' ', $wordarray);
$content = force_balance_tags($content);
endif;
echo "<span class='excerpt'><p>$content</p></span>";
}
}

As you can see here on my website, the descriptions are there, but the length is based on words. Is there anyway I can make the content length of my descriptions based on characters rather than words?

Upvotes: 1

Views: 5320

Answers (1)

Howli
Howli

Reputation: 12469

You can try using the substr() method: e.g.

$content = substr($content, 0, 20);

Where 20 is the amount of characters you want returned.

Code:

add_action( 'woocommerce_after_shop_loop_item_title', 'lk_woocommerce_product_excerpt', 35, 2);
if (!function_exists('lk_woocommerce_product_excerpt'))
{
function lk_woocommerce_product_excerpt()
{
$content_length = 20;
global $post;
$content = $post->post_excerpt;
$wordarray = explode(' ', $content, $content_length + 1);
if(count($wordarray) > $content_length) :
array_pop($wordarray);
array_push($wordarray, '...');
$content = implode(' ', $wordarray);
$content = force_balance_tags($content);
$content = substr($content, 0, 20);

endif;
echo "<span class='excerpt'><p>$content</p></span>";
}
}

Upvotes: 1

Related Questions