Skip Navigation

[Closed] Display only first letter of a field

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

This topic contains 1 reply, has 1 voice.

Last updated by Christopher Amirian 1 month ago.

Assisted by: Christopher Amirian.

Author
Posts
#2823496

Tell us what you are trying to do?
I want to display only the first character of a custom field in the front end. Is there a way to do that?

Is there any documentation that you are following?
https://toolset.com/documentation/legacy-features/views-plugin/conditional-html-output-in-views/#example

Is there a similar example that we can see?
no

What is the link to your site?

#2823825

Christopher Amirian
Supporter

Languages: English (English )

Hi, welcome to Toolset support.

Toolset doesn’t have a built-in shortcode to return just the first character of an arbitrary custom field. The usual (and supported) approach is to add a tiny custom shortcode and use it in your View/Block.

You can create a custom shortcode to handle that like this:

// [first-char field='wpcf-your-field']  or  [first-char]...content...[/first-char]
add_shortcode('first-char', function( $atts, $content = null ) {
    $atts = shortcode_atts(['field' => ''], $atts, 'first-char');

    // Prefer enclosed content; otherwise read a Types field by meta key
    if ($content !== null && $content !== '') {
        $value = do_shortcode($content);
    } elseif ($atts['field']) {
        $value = get_post_meta(get_the_ID(), $atts['field'], true);
    } else {
        $value = '';
    }

    $value = wp_strip_all_tags($value);
    if ($value === '') return '';
    // multibyte-safe first character
    return function_exists('mb_substr') ? mb_substr($value, 0, 1) : substr($value, 0, 1);
});

If you know the field’s meta key (Types fields use wpcf-...):

[first-char field='wpcf-your-field']

Or wrap the Types shortcode (handy when you need formatting or different item):

[first-char][types field='your-field' output='raw' item="@relationship.parent"][/types][/first-char]

The code I suggested above is not tested and we can not support or maintain it as the request is a custom coding. Our goal is to give you a starting point so you can expand or hire a developer to create such a feature for you.

Thanks.

The topic ‘[Closed] Display only first letter of a field’ is closed to new replies.