0

I have this code which will put my category description on the thumbnail tile but i would like to change the code to only show about 80 letters of the total description text, as otherwise my homepage and subcategory listing goes mad and the tiles will be really long. However i would also like the text to display on the category page where the products under it would be displayed and i don't need any limited characters.

Here is my code:

/* Enter your custom functions here */
add_action('woocommerce_after_subcategory_title', 'my_add_cat_description', 12);

function my_add_cat_description ($category) {
    $cat_id=$category->term_id;
    $prod_term=get_term($cat_id,'product_cat');
    $description=$prod_term->description;
    echo '<div class="shop_cat_desc">'.$description.'</div>';
}

Here is my site homepage where you can see the description: https://airsoftcentral.co.uk/

Here is my site where the description is limited: https://airsoftcentral.co.uk/product-category/clothing/

Please let me know if you can advise!

Thanks

James

Matheus Cuba
  • 2,068
  • 1
  • 20
  • 31
Jamyy10
  • 1
  • 1

1 Answers1

0

Assuming that this function is only being called on your homepage, you should be able to add a condition that outputs a substring of the value when it is over 80 characters. Here is a version of your code with the solution added:

/* Enter your custom functions here */
add_action( 'woocommerce_after_subcategory_title', 'my_add_cat_description', 12);
function my_add_cat_description ($category) {
$cat_id=$category->term_id;
$prod_term=get_term($cat_id,'product_cat');

if($description=substr($prod_term->description, 0, 80));
    echo '<div class="shop_cat_desc">'.$description.'</div>';
} else {
    echo '<div class="shop_cat_desc">'.$prod_term->description.'</div>';
}

The condition will return your value if the description is 80+ characters, then you simply echo it. The condition will return false if the description is under 80 characters, in which case, you can just echo the value without assigning it to a variable.

This SO Answer suggests creating a function for it, and they use strlen in their condition, rather than substr, which may be slightly less efficient, but their answer applies here as well.

mtr.web
  • 1,505
  • 1
  • 13
  • 19