Skip to content

Instantly share code, notes, and snippets.

@spivurno
Last active November 10, 2021 19:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save spivurno/e40d7150b739915875ff80c8a2d8f780 to your computer and use it in GitHub Desktop.
Save spivurno/e40d7150b739915875ff80c8a2d8f780 to your computer and use it in GitHub Desktop.
Gravity Perks // Limit Choices // Shared Limits Field
<?php
/**
* WARNING! THIS SNIPPET MAY BE OUTDATED.
* The latest version of this snippet can be found in the Gravity Wiz Snippet Library:
* https://github.com/gravitywiz/snippet-library/blob/master/gp-limit-choices/gplc-shared-choices.php
*/
/**
* Gravity Perks // Limit Choices // Shared Limits Field
*
* Share limits across choices of the same field.
*
* @version 1.0
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link http://gravitywiz.com/documentation/gravity-forms-limit-choices/
*
* Plugin Name: GP Limit Choices — Shared Limits Field
* Plugin URI: http://gravitywiz.com/documentation/gravity-forms-limit-choices/
* Description: Share limits across choices of the same field.
* Author: Gravity Wiz
* Version: 1.0
* Author URI: http://gravitywiz.com
*/
class GPLC_Shared_Limits_Field {
public $_args = array();
public function __construct( $args = array() ) {
// set our default arguments, parse against the provided arguments, and store for use throughout the class
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'field_id' => false
) );
// 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() {
add_filter( 'gplc_choice_counts', array( $this, 'modify_gplc_choice_counts' ), 10, 3 );
}
public function is_applicable_field( $field ) {
$form_id = isset( $field->formId ) ? $field->formId : null;
return $form_id == $this->_args['form_id'] && isset($field->id) && $field->id == $this->_args['field_id'];
}
public function modify_gplc_choice_counts( $counts, $form_id, $field )
{
if( ! $this->is_applicable_field( $field ) ) {
return $counts;
}
$shared_count = 0;
if (is_array($counts)) {
foreach ($counts as $count) {
$shared_count += $count;
}
}
if (is_array($field->choices)) {
foreach ($field->choices as $choice) {
if (isset($choice['limit']) && isset($choice['value'])) {
$counts[$choice['value']] = $shared_count;
}
}
}
return $counts;
}
}
# Configuration
new GPLC_Shared_Limits_Field( array(
'form_id' => 916,
'field_id' => 1
) );
@spivurno
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment