Gravity Wiz // Calculated Shipping
<?php
/**
* Calculated Shipping
*
* A simple method for using a calculated product field as a shipping field. This provides the ability to use
* calculations when determining a shipping price.
*
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link http://gravitywiz.com/...
* @copyright 2013 Gravity Wiz
*/
class GWCalculatedShipping {
function __construct( $args ) {
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'field_id' => false
) );
add_filter( 'gform_pre_submission_filter_' . $this->_args['form_id'], array( $this, 'add_shipping_field' ) );
}
function add_shipping_field( $form ) {
// get our calc shipping field and convert it to default shipping field
$calc_shipping_field = GFFormsModel::get_field( $form, $this->_args['field_id'] );
$calc_shipping_field['type'] = 'shipping';
$calc_shipping_field['inputType'] = 'singleshipping';
$calc_shipping_field['inputs'] = null;
// map calc value as shipping value
$_POST['input_' . $calc_shipping_field['id']] = rgpost( "input_{$calc_shipping_field['id']}_2" );
foreach( $form['fields'] as &$field ) {
if( $field['id'] == $calc_shipping_field['id'] ) {
$field = $calc_shipping_field;
break;
}
}
return $form;
}
function field( $args = array() ) {
return wp_parse_args( $args, array(
'id' => false,
'formId' => false,
'pageNumber' => 1,
'adminLabel' => '',
'adminOnly' => '',
'allowsPrepopulate' => 1,
'defaultValue' => '',
'description' => '',
'content' => '',
'cssClass' => '',
'errorMessage' => '',
'inputName' => '',
'isRequired' => '',
'label' => 'Shipping',
'noDuplicates' => '',
'size' => 'medium',
'type' => 'shipping',
'displayCaption' => '',
'displayDescription' => '',
'displayTitle' => '',
'inputType' => 'singleshipping',
'inputs' => '',
'basePrice' => '$0.00'
) );
}
/**
* Direct port of private method GFFormDisplay::get_max_page_number()
*/
function get_max_page_number( $form ) {
$page_number = 0;
foreach($form["fields"] as $field){
if($field["type"] == "page"){
$page_number++;
}
}
return $page_number == 0 ? 0 : $page_number + 1;
}
}
new GWCalculatedShipping( array(
'form_id' => 375,
'field_id' => 4
) );