Woo Commerce | 452 Views

WooCommerce: Show Short Description with ‘Read More’ Toggle Effect

's Gravatar
Jun 25, 2021
<?php 

/**
 * @snippet       Truncate Short Description @ WooCommerce Single
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.9
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'woocommerce_after_single_product', 'bbloomer_woocommerce_short_description_truncate_read_more' );
 
function bbloomer_woocommerce_short_description_truncate_read_more() { 
   wc_enqueue_js('
      var show_char = 40;
      var ellipses = "... ";
      var content = $(".woocommerce-product-details__short-description").html();
      if (content.length > show_char) {
         var a = content.substr(0, show_char);
         var b = content.substr(show_char - content.length);
         var html = a + "" + ellipses + "Read more" + b + "";
         $(".woocommerce-product-details__short-description").html(html);
      }
      $(".read-more").click(function(e) {
         e.preventDefault();
         $(".woocommerce-product-details__short-description .truncated").toggle();
      });
   ');
}
?>

This code adds a snippet to truncate the short description of a product in WooCommerce and add a “Read more” link to show the full description when clicked.

The code adds an action hook to the woocommerce_after_single_product action, which triggers after the single product page content. The bbloomer_woocommerce_short_description_truncate_read_more() function is called when this action is triggered.

This function adds JavaScript code using the wc_enqueue_js() function to truncate the short description of a product and add the “Read more” link. The JavaScript code sets the number of characters to show initially to 40. If the length of the short description is greater than 40 characters, the code truncates the content and adds the “Read more” link.

When the “Read more” link is clicked, it toggles the visibility of the truncated text and shows the full description.