Skip Navigation

[Resolved] Get the LAST index of a repeating field

This thread is resolved. Here is a description of the problem and solution.

Problem:

I'm utilizing a repeater field to capture the years of each particular model of car. I can easily retrieve the first index with the following:

[types field='vehicle-year' index='0' separator=', '][/types]

My question is how do I retrieve the LAST index item of any particular car?

Solution:

There isn't such kind of built-in feature, you might consider custom codes, for example:

https://toolset.com/forums/topic/get-the-last-index-of-a-repeating-field/#post-2020227

Relevant Documentation:

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 2 replies, has 2 voices.

Last updated by David 5 months, 2 weeks ago.

Assigned support staff: Luo Yang.

Author
Posts
#2020041

I'm utilizing a repeater field to capture the years of each particular model of car. I can easily retrieve the first index with the following:

[types field='vehicle-year' index='0' separator=', '][/types]

My question is how do I retrieve the LAST index item of any particular car? It might be index='5' or index='3', etc. There must be an easy way to retrieve the last item in varying lengths of a repeatable field. Hope that makes sense and thanks!

#2020227

Luo Yang
Supporter

Languages: English (English ) Chinese (Simplified) (简体中文 )

Timezone: Asia/Hong_Kong (GMT+08:00)

Hello,

There isn't such kind of built-in feature, you might consider custom codes, for example:
1) Create a custom shortcode to get the last item's index number:

add_shortcode('last_instances', 'last_instances_func');
function last_instances_func($atts, $content){
    $atts = shortcode_atts( array(
        'field' => '',
        'post_id' => get_the_ID(),
    ), $atts );
      
    $field = get_post_meta($atts['post_id'], $atts['field'], false);
    $res = '';
    if(is_array($field)){
        $res = end($field);
    }
    return $res;
}

2) Use above shortcode to get the last item value, like this:

[last_instances field="wpcf-my-field"]
#2020667

Luo-

That was perfect, thank you! Doing a quick PHP search, I also added the following so I could truncate the second value to just the last two digits:

$res = substr($res, -2);

Now my results look like the following: "2014-21". I appreciate the quick and accurate turn-around. Thanks again.