Skip Navigation

[Resolved] Sumar valores de una lista

This support ticket is created 3 years, 7 months ago. There's a good chance that you are reading advice that it now obsolete.

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.

Sun Mon Tue Wed Thu Fri Sat
- 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 7:00 – 14:00 -
- 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 15:00 – 16:00 -

Supporter timezone: Europe/London (GMT+01:00)

This topic contains 9 replies, has 2 voices.

Last updated by Rafael Corts 3 years, 7 months ago.

Assisted by: Nigel.

Author
Posts
#1746193

Hola Nigel, he creado una lista en un post Type, en esta lista tengo un campo numérico y lo que necesito es sumar los valores de toda la lista, como puedo hacer para sumar estos valores y aparezca el resultado?
Esta lista es dinámica según el filtro que aplique habrá mas o menos campos.
Saludos.
Rafa Corts

#1746963

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Hola Rafa

Necesitarás un shortcode particular para este.

He preparado un ejemplo (creo que será útil para otros) que puedes usar:

/**
 * 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( 
        array(
            'total'     =>   null
        ), 
        $atts
    );
    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;
});

Se usa así:

	[wpv-items-found]
	<!-- wpv-loop-start -->
		<wpv-loop>
          <h3>[wpv-post-link]</h3>
          [sum-item] [types field="number-field"][/types][/sum-item]
		</wpv-loop>
		<h4>[sum-item total=true]</h4>
	<!-- wpv-loop-end -->
	[/wpv-items-found]

Ve como dentro del loop se incluye el campo númerico dentro del shortcode, y después del loop se usa sin contenido pero con el atributo "total" para imprimir el resultado.

#1753531
Captura de pantalla 2020-08-22 a las 10.11.53.png
Captura de pantalla 2020-08-22 a las 10.12.26.png

Hola Nigel ya he creado el schorcode [sum-item] te adjunto imagen, también he puesto el código en la pagina functions y he creado una Vista con este loop:

[wpv-layout-start]
	[wpv-items-found]
	<!-- wpv-loop-start -->
	<table width="100%">
		<tbody class="wpv-loop js-wpv-loop">
		<wpv-loop>
           <h3>[types field='preu-unitat-didactica' format='FIELD_VALUE'][/types] [wpv-post-link]</h3>
      [sum-item][types field="wpv-preu-unitat-didactica"][/types][/sum-item]
    </wpv-loop>
		</tbody>
	</table>
<h4>[sum-item total=true]</h4>
	<!-- wpv-loop-end -->
	[/wpv-items-found]
	[wpv-no-items-found]
		<strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
	[/wpv-no-items-found]
[wpv-layout-end]

En el Field se ha de poner el prefijo? "wpv-preu-unitat-didactica"
lo he probado de las dos maneras y el resultado sigue siendo 0.
Aparentemente no me hace la suma adjunto imagen.
no se que puede suceder.
Saludos.
Rafa Corts

#1753571

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Si se muestra el valor así...

[types field='preu-unitat-didactica' format='FIELD_VALUE'][/types]

Debes usar lo mismo, pero dentro del sum-item shortcode así:

[sum-item][types field='preu-unitat-didactica' format='FIELD_VALUE'][/types][/sum-item]
#1753663

Hola Nigel, no me funciona. Las anotaciones que me has i¡indicado ya estaban implementadas.
No se que puede ser.
Saludos.
Rafa Corts

#1753691

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

¿Puedo acceder al sitio a ver?

#1756041

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Hola Rafa

He modificado el código un poco y ya funciona.

He editado mi respuesta arriba para incluir los cambios.

#1759995

Hola Nigel, he tocado código de la Vista para sumar otro valor y ahora no me funciona, creo que esta todo igual, no se que cambios hiciste para que funcionara.
el codigo de la vista ha quedado asín:

[wpv-layout-start]
	[wpv-items-found]
	<!-- wpv-loop-start -->
	<table width="100%">
		<tbody class="wpv-loop js-wpv-loop">
		<wpv-loop>
             <div class="rc_llistat_uni_caixa">
               <div class="rc_llistat_uni_caixa_nom">
               <h3> [wpv-loop-index accumulate="false" pad="false" offset="0"] [wpv-post-link] </h3></div>
 
                <div class="rc_llistat_uni_caixa_preu">
                [wpv-conditional if="( $(wpcf-preu-unitat-didactica) ne '' )"]
                  <h3> [types field='preu-unitat-didactica' format='FIELD_VALUE'][/types]€</h3>
               [/wpv-conditional]
               </div>
               <div class="rc_llistat_uni_caixa_ingres">
                 [wpv-conditional if="( $(wpcf-valor-ingres) ne '' )"]
                  <h3> [types field='valor-ingres' format='FIELD_VALUE'][/types]€</h3>
                 [/wpv-conditional]
               </div>
             </div> 
          [sum-item][types field='preu-unitat-didactica' format='FIELD_VALUE'][/types][/sum-item]
    </wpv-loop>
		</tbody>
	</table>
				<div class="rc_llistat_uni_caixa">
               <div class="rc_llistat_uni_caixa_num_uni">
               <h3>[wpv-items-count] </h3></div>
                 <div class="rc_llistat_uni_caixa_preu">
                  <h3>[sum-item total=true]€</h3></div>
             </div> 
	<!-- wpv-loop-end -->
	[/wpv-items-found]
	[wpv-no-items-found]
		<strong>[wpml-string context="wpv-views"]No items found[/wpml-string]</strong>
	[/wpv-no-items-found]
[wpv-layout-end]

y en la pagina functions esta sin:

 /**
 * 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( 
        array(
            'total'     =>   null
        ), 
        $atts
    );
    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;
});

Perdona pero si me puedes indicar que es lo que modificaste, me aras un gran favor, no consigo ver donde esta el error.
Si yo quisiera sumar otro valor entiendo que en la pagina functions he de crear otra función para crear un nuevo schortcode, y también crearlo en los setting de toolset.
Mi pregunta es, podré poner el código en la misma vista o debería crear una segunda vista?
Saludos.

#1760007

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

WordPress no tiene soporte nativo para shortcodes dentro de shortcodes y es necesario tener un espacio como mínimo entre el primer shortcode y el segundo, p.j.

[sum-item]<!-- aquí mete un espacio-->[types field='preu-unitat-didactica' format='FIELD_VALUE'][/types][/sum-item]
#1760203

My issue is resolved now. Thank you!

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.