Sum the values of a custom field from each post output by a View

A View outputs posts, and these posts have a numeric custom field. The intention is, at the end of the list of posts, to display the total value from the custom field.

For this you’ll need to register a custom shortcode (“sum-item”) which is used twice. Inside the loop it is used to add another value to the running total. After the loop it is used to output the total itself. Within the loop the custom field value (generated by a types shortcode) is wrapped by the shortcode. After the loop you use the “total” attribute to specify that the shortcode should output the total.

The first part of the code sample is the code to register the shorcode itself, while the second part if an example of how it would be used in the output of a View:

 * Register shortcode to add field values for each item in loop to give total (after loop)
add_shortcode('sum-item', function ($atts=[],$content = null) {
    $atts = shortcode_atts( 
            'total'     =>   null
    static $running = 0;
    $output = "";
    if ( ! is_null( $content ) )
        $content = do_shortcode( ltrim($content) );
        if ( is_numeric( $content ) )
            $running += $content;
    if ( ! is_null( $atts['total'] ) )
        $output = $running;
    return $output;

An example of usage in the loop output of a View:

[sum-item][types field="number-field"][/types][/sum-item]
[sum-item total=true]