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
}
Solutions
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
}
Similar questions
REGEX to target all text between two words including the words
I have a WordPress function which I would like a part of the intercept to be removed. Right now the bellow code works 100% only problem is the text isn't static so I need to make a range for it to work on all pots. This is the code bellow: I tried to make a regex to capture all the text Starting from Samurai Swords, until Plates: but I couldn't as ...
Delete two first words and first words in a string (title wordpress)
currently I use tags in my wordpress article titles and place them at the beginning. https://alerte-prolo.fr/les-alertes-alimentaires/ https://alerte-prolo.fr/alimentaire/acheter-ses-fruits-et-legumes-moins-chers/ I want to keep the tags in the category pages, but in the articles (single.php) I want to delete the tags. currently I use this to lift ...
limit the words in the post content and add read more link
As you can see into the code, the routine is to display the post which has an id of 266. Now all I want is to limit the words displayed in the post content of that post. Let's say, I want to limit the words to a number of 300 and then add a read more link. This is the code I got so far:
Limit the Excerpt field in WP-Admin in words
Is it possible to limit the Excerpt field on the post page in words? Note that I am aware that it's possible to echo the excerpt and limit it in words, but I want the field itself to limit the amount of words, similar to how character limits on text-areas work. Is such thing possible? Maybe a Javascript solution? Maybe something similar to what thi...
Also ask