I found this code on the forum,
https://toolset.com/forums/topic/limit-post-body-content-by-words-cannot-use-exerpt-because-content-has-an-link/
it does the job, trimming the content on carachters [limit_content length="280"]; is it possible to trim in words ?
Thanks in advance for your help
-------------------------------------
add_shortcode('limit_content', 'trim_shortcode');
function trim_shortcode($atts, $content = '')
{
global $post;
$post_data = get_post($post->ID);
$postcontent = $post_data->post_content;
$fielddata = apply_filters('the_content', $postcontent);
//echo "<br><br>Field Data = ".$fielddata;
$length = (int)$atts['length'];
//echo "<br>Length = ".$length;
if (strlen($fielddata) > $length)
{
$trimmedcontent = substr($fielddata, 0, $length) . '…';
}
else
{
$trimmedcontent=$fielddata;
}
//echo "<br><br>Trimemd Content = ".$trimmedcontent;
$content=$trimmedcontent;
return $content;
}
This is the page i'm working on : hidden link
Unfortunately I don't have a simple snippet on hand to extend this code so that it can count words instead of characters. It's not a trivial process to count words because HTML tags may contain spaces, and you have to account for that programmatically. A quick search online led me to this post, which includes some custom code examples you can try:
https://www.pjgalbraith.com/truncating-text-html-with-php/
Thank you Christian
Following yous advice, I modified the code, I'm still counting caracteres, but preventing words to be chopped in half
Here is the code to insert in functions.php if someone needs it
----------------------
/*trim custom field */
add_shortcode('limit_content', 'trim_shortcode');
function trim_shortcode($atts, $content = '') {
global $post;
$post_data = get_post($post->ID);
$postcontent = $post_data->post_content;
$fielddata = apply_filters('the_content', $postcontent);
//echo "<br><br>Field Data = ".$fielddata;
$length = (int)$atts['length'];
//echo "<br>Length = ".$length;
if (strlen($fielddata) > $length) {
$endpos = strpos(str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $fielddata), ' ', $length);
if($endpos !== FALSE)
$trimmedcontent = substr($fielddata, 0, $endpos) . '…';
}
else {
$trimmedcontent=$fielddata;
}
//echo "<br><br>Trimemd Content = ".$trimmedcontent;
$content=$trimmedcontent;
return $content;
}
----------------------------
and the shortcode:
[limit_content length="280"]