Skip to content

Commit 623e4b0

Browse files
authored
Create gpi-shared-choices.php
1 parent 4e18584 commit 623e4b0

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
/**
3+
* Gravity Perks // Inventory // Shared Choices
4+
*
5+
* Share limits across choices in the same field.
6+
*
7+
* Plugin Name: GP Inventory — Shared Choices
8+
* Plugin URI: https://gravitywiz.com/documentation/gravity-forms-inventory/
9+
* Description: Share limits across choices in the same field.
10+
* Author: Gravity Wiz
11+
* Version: 1.0
12+
* Author URI: https://gravitywiz.com
13+
*/
14+
class GPI_Shared_Choices {
15+
16+
public $_args = array();
17+
18+
public function __construct( $args = array() ) {
19+
20+
$this->_args = wp_parse_args( $args, array(
21+
'form_id' => false,
22+
'field_id' => false,
23+
'choices' => array(),
24+
) );
25+
26+
add_action( 'init', array( $this, 'init' ) );
27+
28+
}
29+
30+
public function init() {
31+
32+
add_filter( 'gpi_choice_counts', array( $this, 'modify_choice_counts' ), 10, 3 );
33+
34+
}
35+
36+
public function modify_choice_counts( $counts, $form_id, $field ) {
37+
38+
if ( ! $this->is_applicable_field( $field ) ) {
39+
return $counts;
40+
}
41+
42+
if ( ! empty( $this->_args['choices'] ) ) {
43+
$shared_count = 0;
44+
foreach ( $this->_args['choices'] as $value ) {
45+
$shared_count += rgar( $counts, $value, 0 );
46+
}
47+
} else {
48+
$shared_count = array_sum( $counts );
49+
}
50+
51+
foreach ( $field->choices as $choice ) {
52+
if ( ! isset( $choice['inventory_limit'] ) || ! isset( $choice['value'] ) ) {
53+
continue;
54+
}
55+
if ( ! empty( $this->_args['choices'] ) && ! in_array( $choice['value'], $this->_args['choices'] ) ) {
56+
continue;
57+
}
58+
$counts[ $choice['value'] ] = $shared_count;
59+
}
60+
61+
return $counts;
62+
}
63+
64+
public function is_applicable_field( $field ) {
65+
$form_id = isset( $field->formId ) ? $field->formId : null;
66+
return (int) $form_id === (int) $this->_args['form_id'] && isset( $field->id ) && (int) $field->id === (int) $this->_args['field_id'];
67+
}
68+
69+
}
70+
71+
# Configuration
72+
73+
new GPI_Shared_Choices( array(
74+
'form_id' => 123,
75+
'field_id' => 4,
76+
'choices' => array( 'Second Choice', 'Third Choice' ),
77+
) );

0 commit comments

Comments
 (0)