Skip to content
Advertisement

Limit number of words in Woocommerce description (using php)

I edited my Child Theme’s functions.php to display the short description of my WooCommerce products under the product title.

I had this code that works fine and limits the number of characters to 165, then adds “…” at the end of the excerpt. However, I don’t want the words to break after 165 characters. Therefore, I was wondering if there was a way to either limit the number of words instead of character, or simply keep the words from breaking?

function woocommerce_after_shop_loop_item_title_short_description() {
global $product;

if ( ! $product->post->post_excerpt ) return;
?>
<div itemprop="description">
    <?php echo substr(apply_filters( 'woocommerce_short_description', $product->post->post_excerpt ),0,165);
    echo '...'
    ?>
</div>
<?php

}

Advertisement

Answer

There is a function called wp_trim_words https://developer.wordpress.org/reference/functions/wp_trim_words/ that should do just what you’re looking for. I put 30 as an arbitrary number.

function woocommerce_after_shop_loop_item_title_short_description() {
    global $product;

    if ( !$product->post->post_excerpt ) return;
    ?>
    <div itemprop="description">
        <?php echo wp_trim_words( apply_filters( 'woocommerce_short_description', $product->post->post_excerpt ), 30, '...' );?>
    </div>
    <?php
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement