Gravity Wiz // Gravity Forms // Total Shortcode
<?php
/**
* Gravity Wiz // Gravity Forms // Total Shortcode
*
* Get the total sold or donated per form.
*
* @version 1.1
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link http://gravitywiz.com/
*/
class GW_Total_Shortcode {
public function __construct( $args = array() ) {
// do version check in the init to make sure if GF is going to be loaded, it is already loaded
add_action( 'init', array( $this, 'init' ) );
}
public function init() {
// make sure we're running the required minimum version of Gravity Forms
if ( !property_exists( 'GFCommon', 'version' ) || !version_compare( GFCommon::$version, '1.8', '>=' ) ) {
return;
}
// carry on
add_filter( 'gform_shortcode_total', array( $this, 'shortcode_total' ), 10, 2 );
}
public function shortcode_total( $output, $atts ) {
global $wpdb;
$atts = shortcode_atts(
array(
'id' => false,
'format' => 'currency' // accepted values: false, 'currency', 'comma', 'decimal'
), $atts
);
extract( $atts ); // gives us $id
$form_ids = array_map( 'intval', array_filter( explode( ',', $id ) ) );
$query = array(
'select' => 'SELECT sum( e.payment_amount )',
'from' => "FROM {$wpdb->prefix}gf_entry e",
'where' => 'WHERE e.status = "active"'
);
if ( !empty( $form_ids ) ) {
$query['where'] .= $wpdb->prepare( ' AND e.form_id IN( %d )', implode( ', ', $form_ids ) );
}
$sql = implode( "\n", $query );
$value = round( floatval( $wpdb->get_var( $sql ) ), 2 );
switch ( $format ) {
case 'comma':
case 'decimal':
$thousands = $format == 'decimal' ? '.' : ',';
$decimals = $format == 'decimal' ? ',' : '.';
$output = number_format( $value, 2, $decimals, $thousands );
break;
case 'currency':
$output = GFCommon::to_money( $value );
break;
default:
$output = $value;
break;
}
return $output;
}
}
# Configuration
new GW_Total_Shortcode();