Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bolderelements/7140582d69900cc4f6ce62027bb9a906 to your computer and use it in GitHub Desktop.
Save bolderelements/7140582d69900cc4f6ce62027bb9a906 to your computer and use it in GitHub Desktop.
Add new condition to Table Rate settings page
/**
* Add ability to find and compare the longest length item in Table Rate shipping
* https://codecanyon.net/item/table-rate-shipping-for-woocommerce/3796656?ref=bolderelements
*
* Code should be added to theme's functions.php file
*/
function betrs_add_longest_length_cond( $conditions ) {
// add new option to list
$conditions['longest_length'] = 'Longest Length';
return $conditions;
}
add_filter( 'betrs_shipping_cost_conditionals', 'betrs_add_longest_length_cond', 10, 1 );
function betrs_add_longest_length_cond_secondary( $conditions ) {
// add new option to list
$conditions['greater_than']['conditions'][] = 'longest_length';
$conditions['less_than']['conditions'][] = 'longest_length';
$conditions['equal_to']['conditions'][] = 'longest_length';
return $conditions;
}
add_filter( 'betrs_shipping_cost_conditionals_secondary', 'betrs_add_longest_length_cond_secondary', 10, 1 );
function betrs_add_longest_length_calc( $data, $items ) {
$highest_length = 0;
// determine longest length
foreach( $items as $key => $values ) {
$item_length = $values[ 'data' ]->get_length();
if( $item_length > $highest_length ) {
$highest_length = $item_length;
}
}
// add the new value to the cart data array
$data['longest_length'] = $highest_length;
return $data;
}
add_filter( 'betrs_calculated_totals-per_order', 'betrs_add_longest_length_calc', 10, 2 );
function betrs_determine_condition_longest_length( $return, $cond, $cart_data ) {
// exit if the custom condition is not a dimensional sum
if( sanitize_title( $cond['cond_type'] ) != 'longest_length' ) return $return;
// calculate longest length and init comparison numbers
$comparison = floatval( $cart_data['longest_length'] );
$cond_tertiary = floatval( $cond['cond_tertiary'] );
// determine how to compare the sum to the setting
switch( sanitize_text_field( $cond['cond_secondary'] ) ) {
case 'greater_than':
if( $comparison >= $cond_tertiary )
return true;
break;
case 'less_than':
if( $comparison <= $cond_tertiary )
return true;
break;
case 'equal_to':
if( $comparison == $cond_tertiary )
return true;
break;
}
// return false if the condition is not met
return $return;
}
add_filter( 'betrs_determine_condition_result', 'betrs_determine_condition_longest_length', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment