SOLVED: Number of characters text block

Hi, there is a way to cut the number of characters in text block or in simple text block ?

Hi Paolo,
Welcome to the forum!

If you’re using dynamic data inside of the basic or rich text element you can limit the output to words, but not to characters.

{post_excerpt:25} or {post_title:3}

If it’s just static text, it isn’t possible.

Best regards,
timmse

2 Likes

Hey @timmse. I was having the same issure as @ninmorfeo. Found this thread but couldnt figure out how to apply the post-excerpt for example. I have a basic-text element which gets its data dynamicly from metabox.
How would i apply the excerpt here?
Thanks in advance.
Cheers Omar

1 Like

Hi Omar,
Welcome to the forum!

The dynamic data tag for the (default) post excerpt is:
{post_excerpt}

You can limit the amount of words by adding “:5” for example:
{post_excerpt:5}

The same is true for other dynamic data fields that contain text. So it should also work for your metabox field.

Best regards,
timmse

1 Like

Hi Timmse!

I try to make my own custom tag, to able to use character count and not words count. But It not working, because it count words. What is my mistake? Chatgpt said my code is correct. :smiley:
It woul be wokring like: {post_title:character:2} >>> It would render only the first 2 characters. But is render to me 2 words. :frowning:

add_filter('bricks/dynamic_tags_list', 'register_custom_post_title_tag');
function register_custom_post_title_tag($tags) {
    $tags[] = [
        'name' => '{post_title:character}',  // This is more of a pattern than a static name.
        'label' => 'Post Title Character Limit',
        'group' => 'Custom',
    ];
    return $tags;
}

add_filter('bricks/dynamic_data/render_tag', 'render_post_title_characters', 10, 3);
function render_post_title_characters($tag, $post, $context = 'text') {
    // Using regex to capture the dynamic number of characters
    if (preg_match('/^post_title:character:(\d+)$/', $tag, $matches)) {
        // Get the number of characters to limit to.
        $num_chars = (int) $matches[1];

        // Validate the post object.
        if ($post && isset($post->post_title)) {
            // Use multibyte string function to handle character limit.
            $post_title = $post->post_title;

            // Limit the title to the specified number of characters.
            $trimmed_title = mb_substr($post_title, 0, $num_chars, 'UTF-8');

            // Check if ellipsis is needed.
            if (mb_strlen($post_title, 'UTF-8') > $num_chars) {
                $trimmed_title .= '...';
            }

            return $trimmed_title;
        }
    }

    return $tag; // Return the original tag if no processing occurs.
}